TypeScript中,如何判断一个对象的字段是否为number类型

在TypeScript中,可以使用内联类型注解判断一个对象的字段是否为number类型,例如:

interface MyObject {  
  foo: number;  
  bar?: string;  
}  
  
const myObj: MyObject = { foo: 123, bar: "baz" };  
  
if (typeof myObj.foo === "number") {  
  console.log("myObj.foo is a number");  
} else {  
  console.log("myObj.foo is not a number");  
} // 输出 "myObj.foo is a number"

另外,也可以使用typeof运算符来判断一个对象的字段是否为number类型,例如:

if (typeof myObj.foo === "number") {  
  console.log("myObj.foo is a number");  
} else {  
  console.log("myObj.foo is not a number");  
} // 输出 "myObj.foo is a number"

需要注意的是,使用typeof运算符判断内联类型注解为"number"时,并不能检测出该字段的实际类型是否为number,而只是检测该字段是否为数字类型的值。如果该字段的实际类型不是number,但值是数字,那么typeof运算符也会返回"number"。

posted @ 2023-05-30 11:15  lanedm  阅读(824)  评论(0)    收藏  举报