Home > Blockchain >  Relove return type based on param with default in typescript
Relove return type based on param with default in typescript

Time:10-19

How can this be resolved?

Sandbox

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'.

CodePudding user response:

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

// With optional props
function testOpt(x?: number, def?: false): number | null
function testOpt(x?: number, def?: true): number
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

Playground

This behavior does not supported in TypeScript : true extends T ? number : number | null in a way you expect.

Related issue 24929

  • Related