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

问题描述 投票:1回答:1

请考虑以下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的类型,但是没有成功。

typescript typescript2.0
1个回答
5
投票

我删除了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 :)
}
© www.soinside.com 2019 - 2024. All rights reserved.