簡體   English   中英

定義一個Typescript接口,其中屬性是現有對象的屬性

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

定義接口的最佳方法是,其中屬性之一可以是現有對象上的任何屬性。 在這種情況下,我有一個名為fruits的對象,在這里我只是存儲了許多字符串常量,並且我想定義一個接口(雜貨),以便屬性(fruit)之一可以是fruits對象中的任何字符串常量。

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: []
}

這是我的最佳嘗試,但這會引發錯誤:

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'.

選項之一是切換到字符串枚舉

enum Fruits {
    APPLE = 'APPLE',
    BANANA = 'BANANA',
    ORANGE = 'ORANGE'
}

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

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

另一個選擇是更正現有對象的類型:

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

const fruits: { [key: string]: Fruits } = {
    APPLE: 'APPLE',
    BANANA: 'BANANA',
    ORANGE: 'ORANGE'
}

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

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

fruits鍵值被推斷為字符串。 這會導致錯誤,因為Fruits可分配給字符串類型,反之亦然。

為了避免這種情況,應顯式指定fruits類型:

const fruits: { [K in Fruits]: K } = {
    APPLE: 'APPLE',
    BANANA: 'BANANA',
    ORANGE: 'ORANGE'
};

另一種答案是,使用另一種方法是使用字符串枚舉。 視情況而定,這可能是理想的,也可能是不理想的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM