簡體   English   中英

如何在 Typescript 中引用自己的接口屬性?

[英]How to refer to own property of an interface in Typescript?

我試圖在界面中引用自己的屬性。

讓我們考慮這個例子:

type PizzaType = "pepperoni" | "margherita" | "cheese";

interface Pizza {
    bakeTime: number;
    size: number;
}

interface PizzaService {
    availablePizzaTypes: Record<PizzaType, Pizza>;
    calculatePrice: (type: PizzaType) => number;
}

看看PizzaService.calculatePrice 我們知道類型必須是PizzaType 這很好用。

但是讓我們想象一下,我們不知道PizzaType ,我們只想參考availablePizzaTypes 是這樣的:

interface AnonymousPizzaService {
    availablePizzaTypes: Record<string, Pizza>;
    calculatePrice: (type: << How to refer to `availablePizzaTypes`? >>) => number;
}

我想使用類似type: (keyof availablePizzaTypes)的東西,但這不起作用。

那么我如何在 Typescript 中做類似的事情呢?

編輯這是一個更簡單的例子:

interface Pizza {
    name: string;
    // When `name` is e.g "pepperoni", names can only be "['pepperoni']".
    names: this["name"][];
}

您將需要AnonymousPizzaService的類型參數來捕獲支持的實際比薩餅類型:

type PizzaType = "pepperoni" | "margherita" | "cheese";
interface AnonymousPizzaService<T extends PizzaType> {
    availablePizzaTypes: Record<T, Pizza>;
    calculatePrice: (type: T) => number;
}

游樂場鏈接

暫無
暫無

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

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