定义一个类型,它是数组中对象属性值的列表



我有一个对象数组,它有一个共同的属性& name">

const actionList = [{name: "a"}, {name: "b"}, {name: "c"}]

我将这个数组提供给一个接口,该接口应该接受这个数组和另一个属性,该属性必须允许其中一个"名称"。给定数组的值(所以只有"a"|"b"| "c").

interface Action{
name: string;
}
interface TestInterface<TActions extends Action[] = Action[]>{
actions: TActions;
actionName: TActions[number]["name"]
}

只使用TActions[number]["name"],我得到一个通用的string类型

const a1:TestInterface = { actions: actionList, actionName: "" } // Should only allow "a" | "b" | "c"
const a2:TestInterface = { actions: actionList, actionName: "a" } // Should be ok
const a3:TestInterface = { actions: actionList, actionName: "m" } // Should throw error

有可能吗?

这里有一个游乐场的链接

这是可能的,只要你使你的actionList不可变(例如,通过使用const断言),并提供足够的类型信息编译器:

interface Action{
name: string;
}
const actionList = [{ name: "a" }, { name: "b" }, { name: "c" }] as const;
interface TestInterface<TActions extends readonly Action[] = Action[]>{
actions: TActions;
actionName: TActions[number]["name"]
}
const a1: TestInterface<typeof actionList> = { actions: actionList, actionName: "" }; // Error
const a2: TestInterface<typeof actionList> = { actions: actionList, actionName: "a" }; // OK
const a3: TestInterface<typeof actionList> = { actions: actionList, actionName: "m" }; // Error

相关内容

  • 没有找到相关文章

最新更新