Guilherme Oderdenge
Guilherme Oderdenge

Reputation: 5001

Custom property names

I want to create a function like this:

hello({ x: "hello", y: "world" })

And want to have TypeScript understanding that this is valid:

const greeting = hello({ x: "hello", y: "world" })

greeting.x
greeting.y

But this is not:

// ...

greeting.z

I'm pretty sure that this might be answered somewhere in the webs, but can't figure an appropriate keyword to research properly—that's why I am here.

Upvotes: 0

Views: 59

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073978

You can do that with generics, telling TypeScript that the shape of what it returns is the same as the shape of what it receives:

function hello<T>(obj: T): T {
//            ^^^----^^^-^^^------------------------------------ ***
    return /*...an object with the same shape as `obj`...*/;
}

Using it is exactly as shown in your question.

Live on the playground

Upvotes: 2

Related Questions