I have the following code (nb. this is a simplified version, there are more types allowed than just number or bigint, like time periods, etc.) :
type One<T> = T extends number ? 1 : T extends bigint ? 1n : never;
function one<T extends number | bigint>(arg: T): One<T> {
switch (typeof arg) {
case 'number':
return 1; // ts error : Type '1' is not assignable to type 'One<T>'
case 'bigint':
return 1n; // ts error : Type '1n' is not assignable to type 'One<T>'
default:
throw new TypeError();
}
}
const n = 123;
const bigN = 123n;
// But here Type '1' is indeed assignable to type 'One<T>' where T extends number :
const a: One<typeof n> = 1; // ok `const a: 1`
const b = one(n); // ok `const b: 1`
const c = one(bigN); // ok `const c: 1n`
TS Playground
I don’t understand why I get those errors for the return statements, while everything outside of the function works as expected. Also, if I write return 1 as One<T>
or return 1 as any
, the error goes away.
Is this a typescript issue ? What am I missing here ?