为什么通过通用参数约束添加索引签名

时间:2019-04-24 08:03:52

标签: typescript

我不明白为什么将{ [k: string]: BooleanType2 | ObjectType2 }添加到映射类型的结果中。参见Test2

在不添加索引签名的情况下映射类型的正确方法是什么?

type BooleanType1 = {
  type: 'boolean'
  // optional?: boolean
}

type ObjectType1 = {
  properties: { [k: string]: BooleanType1 | ObjectType1 }
}

type Result1<T extends BooleanType1 | ObjectType1> = [T] extends [ObjectType1]
  ? { [Key in keyof T['properties']]: Result1<T['properties'][Key]> }
  : [T] extends [BooleanType1]
  ? boolean
  : never

type Test1 = Result1<{ properties: { p1: { type: 'boolean' } } }> // Type is { p1: boolean }

type BooleanType2 = {
  type: 'boolean'
  optional?: boolean // This causes "[x: string]: never" to be part of Test2
}

type ObjectType2 = {
  properties: { [k: string]: BooleanType2 | ObjectType2 }
}

type Result2<T extends BooleanType2 | ObjectType2> = [T] extends [ObjectType2]
  ? { [Key in keyof T['properties']]: Result2<T['properties'][Key]> }
  : [T] extends [BooleanType2]
  ? boolean
  : never

type Test2 = Result2<{ properties: { p2: { type: 'boolean' } } }> // Type is { [x: string]: never; p2: boolean }

0 个答案:

没有答案