如何检查我的财产是否存在类型

Dak*_*ito 9 typescript

据我们所知,打字稿允许我们声明部分类型,但是当我们要检查我的属性是否在 keyof 类型中时该怎么办?让我们来看看

interface Car {
   Brand: string;
   Model: string;
}

type KeyofCar = keyof Car; // Brand, Model

if('Brand' is in KeyofCar) {
   something...
} // I know it doesn't work but it is pseudocode
Run Code Online (Sandbox Code Playgroud)

有什么办法可以查到吗?

Dee*_*eeV 3

截至撰写本文时,还没有一种方法可以严格使用 Typescript 机制在运行时检查这一点。虽然你可以做的一个有点丑陋的黑客是创建一个记录,然后从中提取密钥。

interface Car {
   Brand: string;
   Model: string;
}

const carRecord: Record<keyof Car, boolean> = {
  Brand: true,
  Model: true
}

if (carRecord['Brand']) {
  something...
}
Run Code Online (Sandbox Code Playgroud)

您这样做的原因Record是因为每次更改界面时,您也必须更改Record. 否则,Typescript 将抛出编译错误。至少这可以确保检查随着Car接口的增长而保持一致。