Issue
What should I do to declare a function that take a class instance as argument
class Message{
constructor(readonly text:string){}
}
function publish(message:Message){
if(!message instanceof Message){
throw new Error("arg message is not instance of Message")
}
...
}
I would NOT expect the following code to compile
publish({text:"HELLO!"})
but it compiles and for sure the object passed to the function has the same properties but it is not an instance of Message. I would like to enforce the argument to be an insance of that class.
Solution
Typescript uses type signatures to decide if it can compile. Your code will compile because the object of {text: "HELLO"}
matches the signature of the Message
class.
If you have something calling the publish
function after compile, you'll still need to perform the if(message instanceof Message === false)
and throw an error.
Answered By - Dean James
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.