Elnur
Elnur

Reputation: 93

How to get object property values as type from a function argument

here is the short example of what I am trying to achieve

type Arg = {
  name: string
}

function fun(arg: Arg): // what do I return ? 
function fun (arg) {
  return {[arg.name]: true}
}

is there anything I can do about this?

Upvotes: 2

Views: 1012

Answers (1)

I think you are looking for smth like this:

type Arg<T extends string> = {
    name: T
}

function fun<Name extends string, T extends Arg<Name>>(arg: T): Record<T['name'], boolean>
function fun<Name extends string, T extends Arg<Name>>(arg: T) {
    return { [arg.name]: true }
}

const result = fun({ name: 'John' }) // Record<"John", boolean>

Playground

More about infering function arguments, you can find in my article

Upvotes: 2

Related Questions