Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic types in typescript

How would one define the return type of the fn function below?

const fn = (propName1: string, propName2: string) => {
  return { 
   [propName1]: () => true 
   [propName2]: () => 'abc'
  }
}
const x = fn('customProp1', 'customProp2')
console.log(x.customProp1)
console.log(x.customProp2)

e.g.

type FN = (propName: string)=> {
  [propName1]: ()=>true
  [propName2]: ()=>string
}

This is for two custom methods, but ideally the solution should allow for any number of custom methods and properties.

like image 439
TrevTheDev Avatar asked Oct 16 '25 04:10

TrevTheDev


1 Answers

As long as propName is a string, you can do:

type FN_return = {[propName: string]: ()=>true};
like image 184
2pichar Avatar answered Oct 17 '25 18:10

2pichar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!