在 TypeScript 接口中,是否可以将一个 属性 中的键限制为另一个 属性 的值?

In a TypeScript interface, is it possible to limit the keys in one property to the values of another property?

考虑以下 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"}
}

我尝试使用 keyof 和查找类型来限制 obj 的类型,但没有成功。

我删除了 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 :)
}