Reputation: 36876
How can this be resolved?
const test = <T extends boolean>(def: T = false): true extends T ? number : number | null => {
if (def) {
return 1
} else {
return null
}
};
const x = test(true) // expect number
const x1 = test(false) // expect number | null
const x2 = test() // expect number | null
Error:
Type 'boolean' is not assignable to type 'T'.
'boolean' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'boolean'.
Upvotes: 2
Views: 68
Reputation: 33061
You can overload your function:
function test(): number | null
function test(def: false): number | null
function test(def: true): number
function test<T extends boolean>(def?: T) {
if (def) {
return 1 as number
} else {
return null
}
};
const x = test(true) // expect number
const x1 = test(false) // expect number | null
const x2 = test() // expect number | null
SECOND SCENARIO, with second argument
function testOpt(x: number, def: false): number|null
function testOpt(x: number, def: true): number
function testOpt(x: number): number | null
function testOpt(): null
function testOpt(x?: number, def = false): number | null {
if (def) {
return 1 as number
} else {
return null
}
};
const y1 = testOpt(1, true) // expect number
const y2 = testOpt(1, false) // expect number | null
const y3 = testOpt() // expect number | null
const y4 = testOpt(1) // expect number | null
This behavior does not supported in TypeScript : true extends T ? number : number | null
in a way you expect.
Related issue 24929
Upvotes: 2