请考虑以下TypeScript接口:
interface Foo {
list: string[];
obj: { [index: string]: string; };
}
有没有办法指定类型,以便obj
中的键必须是list
中的值之一?
例如,以下内容有效:
class Bar implements Foo {
list = ["key1", "key2"]
obj = {"key1": "value1"}
}
但是,以下是编译错误:
class Bar implements Foo {
list = ["key1", "key2"]
// COMPILE ERROR
// "some-other-key" is not in list
obj = {"some-other-key": "value1"}
}
我试图使用obj
和Lookup Types来限制keyof
的类型,但是没有成功。
我删除了list: string[]
,因为我认为你在运行时并不需要它。此解决方案在编译时工作:
interface Foo<T extends string[]> {
obj: { [index in T[number]]?: string; };
}
class Bar1 implements Foo<["key1", "key2"]> {
obj = {"key1": "value1"} // OK
}
class Bar2 implements Foo<["key1", "key2"]> {
obj = {"some-other-key": "value1"} // Error :)
}