Home » Javascript » Define A Typescript Interface Where A Property Is An Existing Object's Properties

Define A Typescript Interface Where A Property Is An Existing Object's Properties

Posted by: admin June 30, 2018 Leave a comment

Questions:

What is the best way to define an interface where one of the properties could be any of the properties on an existing object. In this case I have an object called fruits where I am simply storing a number of string constants and I want to define an interface (groceries) such that one of the properties (fruit) could be any of the string constants in the fruits object.

type Fruits = 'APPLE' | 'BANANA' | 'ORANGE';

const fruits = {
    APPLE: 'APPLE',
    BANANA: 'BANANA',
    ORANGE: 'ORANGE'
}

interface IGroceries {
    fruit: Fruits,
    vegetables: string[]
}

const initialGroceriesState: IGroceries = {
    fruit: fruits.APPLE,
    vegetables: []
}

This is my best attempt but this will throw an error saying:

Type '{ fruit: string; vegetables: never[]; }' is not assignable to type 'IGroceries'.
  Types of property 'fruit' are incompatible.
    Type 'string' is not assignable to type 'Fruits'.
Answers: