如何将属性转换为布尔值(深)

时间:2019-05-31 06:54:03

标签: javascript node.js typescript

我想将每种类型都强制转换为booleanobject

type CastDeep<T, K = boolean> = {
  [P in keyof T]: K extends K[]
    ? K[]
    : T[P] extends ReadonlyArray<K>
      ? ReadonlyArray<CastDeep<K>>
      : CastDeep<T[P]>
}
interface ITest {
  city: {
    name: string,
  }
}

预期结果:

excludeProps<ITest>({
   city: true,
});

excludeProps<ITest>({
 city: {
  name: true
 },
});

当前错误消息:

  19     name: string,
           ~~~~
    The expected type comes from property 'name' which is declared here on type 'CastDeep<{ name: string; }, boolean>'

1 个答案:

答案 0 :(得分:2)

好,找到解决方法

export type ICastDeep<T> = {
  [P in keyof T]: boolean | ICastDeep<T[P]>;
}