Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Typesafety in a function that accepts callback function in Typescript

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yes, with the use of generics you can:

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

Playground Link

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading