条件参数类型的类型保护
Type guard on conditional parameter type
为什么此代码不起作用?
Typescript 很容易猜到 (T extends '1' ? '1' : never)
类型的变量永远不会是 false
,因此 NonFalse<TypeWithCondition<T>>
与 true | (T extends '1' ? '1' : never)
.[=15= 完全相同]
这是打字稿错误吗?它应该作为功能请求发布吗?
type TypeWithCondition<T> = boolean | (T extends '1' ? '1' : never);
type NonFalse<T> = Exclude<T, false>;
const logNonFalse = <T>(b: NonFalse<TypeWithCondition<T>>) => {
console.log(b);
};
const test1 = <T>(a: TypeWithCondition<T>) => {
if (a === false) throw new Error("Can't be false");
logNonFalse(a);
// Error : Argument of type 'true | ([T] extends ["1"] ? "1" : never)' is not assignable to parameter of type 'true'.
// Type '[T] extends ["1"] ? "1" : never' is not assignable to type 'true'.
// Type '"1"' is not assignable to type 'true'.(2345)
};
Typescript 还不能处理这个问题。比照https://github.com/microsoft/TypeScript/issues/38863
为什么此代码不起作用?
Typescript 很容易猜到 (T extends '1' ? '1' : never)
类型的变量永远不会是 false
,因此 NonFalse<TypeWithCondition<T>>
与 true | (T extends '1' ? '1' : never)
.[=15= 完全相同]
这是打字稿错误吗?它应该作为功能请求发布吗?
type TypeWithCondition<T> = boolean | (T extends '1' ? '1' : never);
type NonFalse<T> = Exclude<T, false>;
const logNonFalse = <T>(b: NonFalse<TypeWithCondition<T>>) => {
console.log(b);
};
const test1 = <T>(a: TypeWithCondition<T>) => {
if (a === false) throw new Error("Can't be false");
logNonFalse(a);
// Error : Argument of type 'true | ([T] extends ["1"] ? "1" : never)' is not assignable to parameter of type 'true'.
// Type '[T] extends ["1"] ? "1" : never' is not assignable to type 'true'.
// Type '"1"' is not assignable to type 'true'.(2345)
};
Typescript 还不能处理这个问题。比照https://github.com/microsoft/TypeScript/issues/38863