【发布时间】:2018-04-25 09:09:19
【问题描述】:
我想创建一个Partial 类型的对象,其中的键是“a”、“b”或“c”的某种组合。它不会有所有 3 个键(编辑:但它至少有一个)。如何在 Typescript 中执行此操作?以下是更多详细信息:
// I have this:
type Keys = 'a' | 'b' | 'c'
// What i want to compile:
let partial: Partial = {'a': true}
let anotherPartial: Partial = {'b': true, 'c': false}
// This requires every key:
type Partial = {
[key in Keys]: boolean;
}
// This throws Typescript errors, says keys must be strings:
interface Partial = {
[key: Keys]: boolean;
}
我在上面尝试过的两种方法(使用映射类型和接口)都没有达到我想要的效果。有人可以帮忙吗?
【问题讨论】:
标签: javascript string typescript object key