3

I have the following interface:

interface Address {
   street: string
   town: string
   country: string
}

I want a function to accept a key parameter that has to be one of three strings:

function useKey(key: "street" | "town" | "country") {
}

Can I somehow generate the type for the key parameter from the interface?

1

2 Answers 2

4

Typescript has the keyof type operator for this exact specific case:

function useKey(key: keyof Address ) {
}

This will give you all the public keys of a type in a union.

You can use type queries to even get to the type of the filed:

function getValue<K extends keyof Address>(key: K): Address[K]{
     //...
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can use keyof operator:

type AddressKey = keyof Address

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.