【发布时间】:2018-08-14 18:05:01
【问题描述】:
TypeScript 中有没有办法创建 Advanced types 文档中提到的 Flags 类型的嵌套版本?
这很好用:
type Flags<T> = {
[P in keyof T]: boolean;
}
interface Colors {
red: string;
green: string;
blue: string;
}
const activeColors: Flags<Colors> = {
red: true,
green: true,
blue: false
}
但是,如果我想创建一个能够处理这样的嵌套对象的 NestedFlags 类型呢?
interface NestedColors {
red: string;
green: string;
blue: string;
more: {
yellow: string;
violet: string;
black: string;
}
}
const activeNestedColors: NestedFlags<NestedColors> {
red: true,
blue: false,
green: true,
more: {
yellow: false,
violet: true,
black: true
}
}
我可以用[P in keyof T]: boolean | NestedFlags<T[P]> 创建一个NestedFlags 类型。该解决方案效果很好,只是它允许我使用例如创建一个对象。 more: false 在我的情况下是不可取的。
谢谢!
【问题讨论】: