以下是MyClass
:
export class MyClass {
one: string;
two: string;
constructor(init?: Partial<MyClass>) {
if (init) {
Object.assign(this, init);
} else {
this.one = 'first';
this.two = 'second';
}
}
getOneAndTwo(): string {
return `${this.one} and ${this.two}!`;
}
}
以下是实例化MyClass
的三种方法:
import { MyClass } from './models/my-class';
let mine = new MyClass();
console.log(mine.getOneAndTwo());
mine = new MyClass({
one: 'One',
two: 'Two'
});
console.log(mine.getOneAndTwo());
mine = {
one: 'Three',
two: 'Four'
} as MyClass;
console.log(mine.getOneAndTwo());
对getOneAndTwo()
的最后一次调用会抛出一个错误,就像这样:
TypeError: mine.getOneAndTwo is not a function
at Object.<anonymous>
我假设TypeScript编译器允许这个编译,因为它假设我正在处理类似TypeScript接口的TypeScript类。有什么方法可以发出警告或错误来防止这种假设发生?
答案 0 :(得分:1)
我认为没有任何开箱即可执行您想要的检查。来自TS Handbook:
输入断言
有时你最终会遇到一个比TypeScript更了解价值的情况。通常,当您知道某个实体的类型可能比其当前类型更具体时,就会发生这种情况。
类型断言是一种告诉编译器“信任我,我知道我在做什么。”的方法。类型断言就像在其他语言中使用类型转换,但不执行特殊的数据检查或重组< / strong>即可。它没有运行时影响,纯粹由编译器使用。 TypeScript假定您(程序员)已执行了您需要的任何特殊检查。
我认为可以检查mine
是否属于MyClass
类型,但可能不是最实用的解决方案IMO
let mine = new MyClass({
one: 'One',
two: 'Two'
});
console.log(mine instanceof MyClass); //true
mine = {
one: 'Three',
two: 'Four'
} as MyClass;
console.log(mine instanceof MyClass); // false