如何声明一个以类实例为参数的函数
class Message{
constructor(readonly text:string){}
}
function publish(message:Message){
if(!message instanceof Message){
throw new Error("arg message is not instance of Message")
}
...
}
我不希望以下代码能够编译
publish({text:"HELLO!"})
但它编译并且肯定传递给函数的对象具有相同的属性,但它不是 Message 的实例。 我想强制该参数成为该类的实例。
答案 0 :(得分:0)
Typescript 使用类型签名来决定它是否可以编译。您的代码将被编译,因为 {text: "HELLO"}
的对象与 Message
类的签名相匹配。
如果您在编译后调用了 publish
函数,您仍然需要执行 if(message instanceof Message === false)
并抛出错误。