Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 如何检查类型中是否存在我的属性_Typescript - Fatal编程技术网

Typescript 如何检查类型中是否存在我的属性

Typescript 如何检查类型中是否存在我的属性,typescript,Typescript,据我们所知,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 pseudoco

据我们所知,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

有没有办法找到答案?

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

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

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

if (carRecord['Brand']) {
  something...
}
接口车{
品牌:弦;
模型:字符串;
}
const carRecord:记录={
布兰德:没错,
模型:正确
}
if(carRecord[“品牌]){
某物
}

之所以要执行
记录
,是因为每次更改界面时,都必须更改
记录
。否则,Typescript将抛出编译错误。这至少可以确保检查在
Car
接口增长时保持一致

我不知道你来这里干什么。在您的问题中,您在编译时知道
品牌
位于
汽车钥匙中。那你为什么要检查它

我可以想象,如果类型不完全已知,比如在类型参数中尝试这样做

function<T>(foo: T) {
  if('bar' in keyof T) {
    // do something...
  }
}
如果你真的想用钥匙做点什么,你可以这样做

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

interface Bus {
  Passengers: number;
  Color: string;
}

function(foo: Car | Bus) {
  if('Brand' in foo) {
    // foo is a Car
  } else {
    // foo is a Bus
  }
}
type CarKey = keyof Car;
const carKeys: CarKey[] = ['Brand', 'Model'];

function(key: string) {
  if(carKeys.includes(key)) {
    // do thing
  }
}
类型CheckPropExists=T[Prop]扩展未定义?假:真;
//范例
类型结果=CheckPropertExists;
//结果是真的

我认为目前不能用接口实现这一点,请看。我知道接口是抽象类型,所以很难达到我想要的,但可能有人发现了解决方案。效果很好,但它适用于字符串类型,而不是字符串变量。。。
type CheckPropExists<T extends {[x:string]:any},Prop extends string> = T[Prop] extends undefined ? false : true;
//Example
type Result = CheckPropExists<{a:string;b:number;},"a">;
//Result is true