如何验证对象是否具有接口(interface)的所有属性。
例如:
interface Vehicle {
name: string
model: string
}
interface User {
Name: string
age: númber
}
interface Customer extends User {
vehicles: Vehicle[]
}
如何检查对象是否具有 Customer
接口(interface)的所有属性???
最佳答案
如果你的意思是静态类型检查...
如果“验证对象是否具有接口(interface)的所有属性”,您的意思是静态类型检查,那么这就是 Typescripts 的工作,当您将对象分配给该接口(interface)类型的变量。例如:
const obj = {name: 'Edwin', age: 35}
let c: Customer = obj // this will fail at compile time
如果您的意思是运行时类型检查...
运行时的Typescript只是Javascript,而Javascript不支持接口(interface)定义。事实上,一旦 Typescript 在执行前转译为 Javascript,Vehicle
、User
和 Customer
将不再存在,因为键入删除。有关更多信息,请参阅这些 this和 this在 Typescript 手册和文档中。这意味着您甚至无法在任何运行时逻辑中引用这些类型。
Javascript instanceof
运算符仅适用于 Javascript 原型(prototype)继承,并且具有非常具体的含义:
The instanceof operator tests to see if the prototype property of a constructor appears anywhere in the prototype chain of an object. The return value is a boolean value.
Javascript typeof
运算符仅适用于基本类型,例如 string
。
如果您需要执行运行时“类型检查”,则必须手动执行此操作,以递归方式检查每个字段是否存在及其原始类型。
Typescript 有一些语法糖,可以使此类手动检查在 Typescript 源代码中看起来很自然。了解 Narrowing and Type Guards .
有一些库可以为您执行此操作。以下是一些示例(还有更多):
关于javascript - 如何确保对象符合 Typescript 接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70254786/