打字稿:条件类型不会评估函数泛型类型

时间:2021-06-03 22:29:16

标签: typescript generics types conditional-statements calculation

我的代码:

type getType<t> = t extends string ? string : number
function fun<A extends string>(a: A) {
    var x: getType<A> = 'abc'
}

getType 是一种类型计算。如果输入类型为string,则返回string,否则返回number

在函数fun中,有一个x类型的变量getType<A>

因为我说的是 A extends string,所以说 getType<A>string 是合乎逻辑的。

但 TypeScript 不会推断出这一点。 TypeScript 抱怨:Type 'string' is not assignable to type 'getType<A>'

为什么会这样?

提前致谢。

0 个答案:

没有答案