Home > Enterprise >  Typesafety in a function that accepts callback function in Typescript
Typesafety in a function that accepts callback function in Typescript

Time:06-21

Consider the following code in TS playground here

In line 14, is it possible to throw error for "tree" variable, i.e. it does not exist in the returned object for it to be destructured ?

const foo = () => ({
  bar: {
    hi: 5
  },
  six: {
    max: 10
  }
})

function test(fn: () => Record<string, Object>) {
  return fn()
}

const {six, tree } = test(foo) // <- line 14

console.log(tree)

CodePudding user response:

Yes, with the use of generics you can:

function test<R extends Record<string, Object>>(fn: () => R): R {
    return fn()
}

Playground Link

  • Related