英文:
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<T extends unknown> = unknown extends T ? number : boolean;
type T1 = TEST<unknown>; // number
type T2 = TEST<string>; // boolean
Check it online.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论