TypeScript 映射类型:带有嵌套的标志类型



有没有办法在TypeScript中创建高级类型文档中提到的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
  }
}

我能够创建一个NestedFlags类型与[P in keyof T]: boolean | NestedFlags<T[P]>.该解决方案效果很好,除了它允许我使用 eg 创建一个对象。 more: false,这在我的情况下是不可取的。

谢谢!

您可能希望映射的条件类型(从 TypeScript v2.8 开始(在本月(2018 年 3 月(的某个时候发布。 您现在可以将其与 typescript@next . 这是我如何实现它的第一个镜头:

type NestedFlags<T> = {
  [K in keyof T]: T[K] extends object ? NestedFlags<T[K]> : boolean
}

上面的行使用条件类型三元类型语法。 这意味着:对于T中的每个键,NestedFlags<T>的属性类型将取决于原始属性是否是对象类型。 如果原始属性不是对象类型,则相应的属性将为布尔值。 如果原始属性对象类型,则相应的属性将是应用于该对象类型的NestedFlags<>

这将为您提供以下行为:

interface NestedColors {
  red: string;
  green: string;
  blue: string;
  more: {
    yellow: string;
    violet: string;
    black: string;
  }
}
// okay    
const activeNestedColors: NestedFlags<NestedColors> = {
  red: true,
  blue: false,
  green: true,
  more: {
    yellow: false,
    violet: true,
    black: true
  }
}
// error
const badActiveNestedColors: NestedFlags<NestedColors> = {
  red: true,
  blue: false,
  green: true,
  more: false
} 
// Types of property 'more' are incompatible.
// Type 'boolean' is not assignable to ...

TypeScript 抱怨badActiveNestedColors,说more不应该是boolean

希望有帮助。 祝你好运!

最新更新