How to define the possible values of a string in an iterface from an object?

Asked

Viewed 41 times

3

I have that class Item:

class Item {
  nome: string;
  idade: number;
}

And that interface ConfItem:

interface ConfItem<TypeItem> {
  titulo: string;
}

How do I make for the title in ConfItem accepted only as a string value keys of Item which is received by TypeItem?

I need something like this:

interface ConfItem<TypeItem> {
  titulo: 'nome' | 'idade' 
}

But it has to be dynamic, because ConfItem will be generic, and therefore can receive any TypeItem.

1 answer

3


You can use the keyof, that returns a Union type of strings containing all object keys.

Then you’d have something like:

interface ConfItem<TypeItem> {
  titulo: keyof TypeItem 
}

See the example above on Typescript playground.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.