0

Is there a way in Typescript to use a known type as the key of an interface, dynamically?

For example, I have this type:

type properties = 'name' | 'age' | 'height';

and I want to allow an object that uses any/all of those "properties" as the key, and a string as the value:

{name: 'abc', height: '2'} or {height: '2'} allowed

I've done this with values, but not keys, so I'd want the opposite of this:

interface person {
  [key: string]: properties
}

Something like this:

interface person {
  [key: properties]: string
}
1
  • 1
    type person = { [key in properties]?: string } Commented Jul 15, 2020 at 0:09

1 Answer 1

2

You can use type for that:

type Properties = 'name' | 'age' | 'height';
type Person = {
    [key in Properties]: string
}

// This is allowed
const allowed: Person = {
    name: 'the-name',
    age: '21',
    height: '180',
}

// This has error
const errored: Person = {
    name: 'the-name',
    age: '21',
    height: '180',
    anotherKey: 'foo',
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks! i added ?: string to satisfy the optional cases.

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.