首页 > 解决方案 > 我可以根据类型定义接口吗?

问题描述

如何根据类型定义带有键的接口?例如:

type FruitTypes = "bananna" | "appple " | "orange";

interface FruitInterface {
  [key: string]: any; // key FruitTypes instead of string
}

// Expected result:
const FruitsObject: FruitInterface = {
  bananna: "Bannana",
  apple: "Apple",
  orange: "Orange",
  mango: "Mango" // Error
};

我试过这样的事情:

interface FruitInterface {
  [key: keyof FruitTypes]: any;
}

也许还有另一种方法吗?

提前致谢。

标签: typescript

解决方案


这就像您希望的那样:

const FruitsObject: Record<FruitTypes, any>

您需要接口是否有特定原因?这也是可能的:

interface FruitInterface extends Record<FruitTypes, any> {}
const FruitsObject: FruitInterface

推荐阅读