Typescript: conditional types,但是当 equals 而不是 when extends

huangapple go评论64阅读模式
英文:

Typescript: conditional types, but when equals not when extends

问题

需要确定基于提供的 T 是否确切为 unknown,来确定 TEST<T> 的类型。正如某些 TypeScript 专家已经告诉我一样,每种类型都是从 unknown 继承的,因此下面的代码不应该起作用:

type TEST<T> = T extends unknown ? number : boolean;

type T1 = TEST<unknown>; //期望是数字,确实是数字
type T2 = TEST<string>; //期望是布尔,但实际上是数字

如何实现预期的结果?我能否测试类型相等而不是扩展性?

英文:

I need to determine Type TEST<T> based on if provided one T is exactly unknown. As certain Typescript Wizard told me already, every type extends from unknown so this code below shouldn't work:

type TEST<T> = T extends unknown ? number : boolean;

type T1 = TEST<unknown>; //expecting number and it is number
type T2 = TEST<string>; //expecting boolean ant it's not, it's number too

How can I achieve expected results? Can I test type equality instead of extendness?

答案1

得分: 0

根据 @jcalz 的评论,解决您的问题的一个解决方案可以是:

type TEST<T extends unknown> = unknown extends T ? number : boolean;

type T1 = TEST<unknown>;    // number
type T2 = TEST<string>;     // boolean

在线查看:链接

英文:

Based on @jcalz's comment, one solution to your problem could be:

type TEST&lt;T extends unknown&gt; = unknown extends T ? number : boolean;

type T1 = TEST&lt;unknown&gt;;    // number
type T2 = TEST&lt;string&gt;;     // boolean

Check it online.

huangapple
  • 本文由 发表于 2023年3月7日 23:50:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75664221.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定