d-_-b
d-_-b

Reputation: 23211

Typescript interface allowing key of type, and string values

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
}

Upvotes: 0

Views: 529

Answers (1)

Kousha
Kousha

Reputation: 36299

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',
}

Upvotes: 2

Related Questions