Typescript严格检查条件类型中的类型



在下面的代码中,我希望type Atrue,而不是两者的并集:

type isFalseAndNotAny<T> = T extends false ? 'false' : 'true';
// how do I get here only `true`?
type A = isFalseAndNotAny<any>; 

// that's OK we get only `false`    
type B = isFalseAndNotAny<false>;

是否有任何方式在Typescript做类似的东西在Javascript中,我们使用三重相等===操作符?

您需要稍微修改一下您的util。

// credits goes to https://stackoverflow.com/questions/55541275/typescript-check-for-the-any-type
type IfAny<T, Y, N> = 0 extends (1 & T) ? Y : N;
type IsAny<T> = IfAny<T, true, false>;
type isFalseAndNotAny<T> = T extends false ? IsAny<T> extends false ? 'false' : 'true' : 'true';
// true
type A = isFalseAndNotAny<any>;
// false
type B = isFalseAndNotAny<false>;

您需要明确检查T是否扩展了false而不是any,它类似于T===false && T!==any

最新更新