Typescript不会生成错误。
我强制一个错误,看看打字稿的表现如何,并没有产生我预期的错误。
我创建了一个类型为boolean的类。然后我创建了一个界面。我创建了构造函数方法来初始化变量。所以我得到一个json,其中变量的类型为string。令我惊讶的是,boolean变量接收字符串。我希望它会产生错误。我的代码不尊重变量的类型。
export class Product{
public status:boolean;
constructor(obj?: IProduct) {
if(obj)
{
this.status = obj.status;
}
}
}
interface IProduct {
status:boolean;
}
我的服务器json
{status: "test"}
将测试值分配给状态变量。这不应该被允许。
有谁知道如何确保变量只接收布尔值?
答案 0 :(得分:4)
运行时没有类型强制执行。
Decorators(实验性功能)可以解决您的问题:
class Product {
@validate
public status: boolean;
constructor(obj?: IProduct) {
if(obj) {
this.status = obj.status;
}
}
}
interface IProduct {
status: string;
}
function validate(target: any, propertyKey: string) : any {
if (propertyKey === "status") {
return {
set: function (value: any) {
if (typeof value !== "boolean") {
throw new Error("The supplied value is not of type boolean");
}
}
}
}
}
答案 1 :(得分:1)
它可能与您的接口
有关interface IProduto { // typo it should be IProduct
nome:boolean; // and this should be name i suppose but i left it nome
}
如果您想确保所有值必须具有指定的类型,您可以在 tsconfig.json 中将 noImplicitAny 设置为true,这意味着TS类。
答案 2 :(得分:1)
尝试:
interface IProduct {
status: Boolean;
}
注意界面拼写错误并将nome更改为状态。
答案 3 :(得分:0)
您可以在构造函数中使用此if语句:
if (typeof obj !== 'boolean') {
throw Error('type of obj must be boolean');
}