Home > Software design >  Typescript: how to set type as a key of interface
Typescript: how to set type as a key of interface

Time:09-23

Say I have an interface:

interface ExampleInterface {
  someItem: 'a' | 'b' | 'c'
  anotherItem: boolean
  lastItem: string
}

Say I want to set the type in another interface as ExampleInterface.someItem like:

 interface ExampleInterface2 {
  newItem: ExampleInterface.someItem
}

I don't want to create type SomeItem = 'a' | 'b' | 'c' and then set it in both. I'm trying to use an interface in an external typescript library.

is this possible?

CodePudding user response:

I figure it out for anyone with the same issue:

interface ExampleInterface {
  someItem: 'a' | 'b' | 'c'
  anotherItem: boolean
  lastItem: string
}

interface ExampleInterface2 {
  newItem: ExampleInterface['someItem']
}

CodePudding user response:

Yep, this is possible!

 interface ExampleInterface2 {
  newItem: ExampleInterface["someItem"]
}
  • Related