简体   繁体   English

"Typescript:当键是宽类型时,是否定义了对象属性的类型保护?"

[英]Typescript: type guard for whether an object property is defined, when the key is a wide type?

I have a function that returns whether an object property is undefined .我有一个返回对象属性是否为undefined的函数。 I need this function instead of just doing obj[key] === undefined because otherwise I'd sometimes get Property 'foo' does not exist on type 'Bar'.我需要这个函数而不是仅仅做obj[key] === undefined因为否则我有时会得到Property 'foo' does not exist on type 'Bar'. . . It's straightforward to write the type when the property key is a literal.当属性键是文字时,编写类型很简单。 Ie: IE:

function hasDefinedProp<
  Obj extends Partial<Record<string, any>>,
  Prop extends string,
>(
  obj: Obj,
  prop: Prop,
): obj is Obj & Record<Prop, Prop extends keyof Obj ? Exclude<Obj[Prop], undefined> : unknown> {
  return obj[prop] !== undefined;
}

const obj: Partial<Record<string, number>> = {};
if (hasDefinedProp(obj, 'foo')) {
    obj.foo + 1; // No error.
    obj.bar + 1; // "Object is possibly 'undefined'."
}

However, this doesn't work when the key's type is a wide type, ie:但是,当键的类型是宽类型时,这不起作用,即:

const obj: Partial<Record<string, number>> = {};
const key: string = '';
if (hasDefinedProp(obj, key)) {
    obj[key] + 1; // No error.
    obj.bar + 1; // No error. Should be "Object is possibly 'undefined'."
}

Is it possible to make the type guard work for wide types?是否可以使类型保护适用于宽类型?

AFAIK, it is not possible. AFAIK,这是不可能的。 Once you have added explicit string<\/code> type to const key: string = '';<\/code>将显式string<\/code>类型添加到const key: string = '';<\/code> - TS is unable to narrow literal type of key<\/code> . -TS 无法缩小key<\/code>的文字类型。 As a result, you are allowed to use any string you want to access a property.因此,您可以使用任何想要访问属性的字符串。 TS is unable to distinguish two types with type string<\/code> in this example:在这个例子中,TS 无法区分两种类型为string<\/code>的类型:

const obj: Partial<Record<string, number>> = {};
const key: string = '';
if (hasDefinedProp(obj, key)) {
    obj[key] + 1; // No error.
    obj.bar + 1; // No error. Should be "Object is possibly 'undefined'."
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM