如何防止在 TypeScript 中分配错误的类型?
How to prevent assignment of wrong type in TypeScript?
我是 TypeScript 的新手,想摆脱潜入我的数据结构的错误类型。我认为 TypeScript 会禁止 this.myString = myArgument
的以下赋值,因为 myArgument
的类型未知。
class MyClass {
private myString : string;
constructor(myArgument) {
this.myString = myArgument;
}
}
let myInstance = new MyClass(3);
console.log("my instance", myInstance);
在运行时 myInstance.myString
将是一个非常不受欢迎的数字 :( 我知道我可能可以添加 myArgument : string
作为参数参数类型声明,但我认为 TypeScript 的优势之一是类型推断这应该很容易?
如何防止错误的类型出现在我的数据结构中?
如果您想确保所有值都必须具有指定的类型,您可以在 tsconfig.json
.
中将 noImplicitAny
设置为 true
我是 TypeScript 的新手,想摆脱潜入我的数据结构的错误类型。我认为 TypeScript 会禁止 this.myString = myArgument
的以下赋值,因为 myArgument
的类型未知。
class MyClass {
private myString : string;
constructor(myArgument) {
this.myString = myArgument;
}
}
let myInstance = new MyClass(3);
console.log("my instance", myInstance);
在运行时 myInstance.myString
将是一个非常不受欢迎的数字 :( 我知道我可能可以添加 myArgument : string
作为参数参数类型声明,但我认为 TypeScript 的优势之一是类型推断这应该很容易?
如何防止错误的类型出现在我的数据结构中?
如果您想确保所有值都必须具有指定的类型,您可以在 tsconfig.json
.
noImplicitAny
设置为 true