Why is this code not working ?
Typescript could easily guess that a variable of type (T extends '1' ? '1' : never)
will never be false
, so that NonFalse<TypeWithCondition<T>>
is exactly the same than true | (T extends '1' ? '1' : never)
.
Is it a Typescript bug ? Should it be posted as a Feature Request ?
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 is not yet able to handle that. Cf https://github.com/microsoft/TypeScript/issues/38863