繁体   English   中英

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

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

我有一个名为T的类型,它接受泛型类型Str extends string 如果Str扩展了"hello" ,那么类型T应该有一个称为B的附加属性。 像这样的东西:

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

基于该类型,它的行为如下:

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

现在,我想创建一个接受此类型作为参数的 function,并根据属性B的存在添加一个额外的逻辑:

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

虽然,我收到一个错误,即 if 语句中的arg被视为never

看游乐场

如果您明确命名变体,它会起作用:

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);
  }
}

游乐场链接

实际上需要命名的是该字符串是“hello”的可能性。 这是更简化的版本:

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);
  }
}

关联

暂无
暂无

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

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