简体   繁体   English

在检查条件属性是否存在时,Typescript 将 object 推断为从不

[英]Typescript infers object as never when checking if a conditional property exists

I have a type called T that accepts a generic type Str extends string .我有一个名为T的类型,它接受泛型类型Str extends string If the Str extends "hello" , then the type T should have an additional property called B .如果Str扩展了"hello" ,那么类型T应该有一个称为B的附加属性。 Something like this:像这样的东西:

export type T<Str extends string> = {
  A: number;
} & (Str extends "hello" ? { B?: number } : {});

Based on that type, it behaves as follows:基于该类型,它的行为如下:

type T1 = T<"hello">; // type T1 = { A: number; B?: number | undefined; }
type T2 = T<"world">; // type T2  = { A: number; }

Now, I want to create a function that accepts this type as an argument, and add an extra logic based on the existence of property B :现在,我想创建一个接受此类型作为参数的 function,并根据属性B的存在添加一个额外的逻辑:

function t<Type extends string>(arg: T<Type>) {
  if ("B" in arg) {
    // ...
  }
}

Although, I get an error that arg inside the if statement is considered as never .虽然,我收到一个错误,即 if 语句中的arg被视为never

See playground 看游乐场

It works if you explicitly name the variant:如果您明确命名变体,它会起作用:

export type Test<Str extends string> = {
  A: number;
} & (Str extends "hello" ? { B?: number } : { });

type HelloVariant = Test<"hello">;

function t<T extends (HelloVariant | Test<string>)>(arg: T) {
  if ("B" in arg) {
    console.log(arg.B);
  }
}

Playground Link 游乐场链接

Actually what needs to be named is the possibility of that string being a "hello".实际上需要命名的是该字符串是“hello”的可能性。 Here is more simplified version:这是更简化的版本:

export type Test<Str extends string> = {
  A: number;
} & (Str extends "hello" ? { B?: number } : { });

function t<T extends (Test<"hello"> | Test<string>)>(arg: T) {
  if ("B" in arg) {
    console.log(arg.B);
  }
}

Link 关联

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

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