代码之家  ›  专栏  ›  技术社区  ›  Camilo

为什么TypeScript只返回extends的一个分支?

  •  -1
  • Camilo  · 技术社区  · 7 月前

    假设我们有:

    const func = (
      multiple: boolean
    ) => {
      type Value = typeof multiple extends true ? string[] : string
    
      if (multiple) {
        const foo: Value = ['string']
      } else {
        const bar: Value = 'string'
      }
    }
    

    这会导致以下TypeScript错误 foo :

    Type 'string[]' is not assignable to type 'string'.(2322)
    

    我在等 Value 成为 string[] 如果 multiple true 我错过了什么?

    1 回复  |  直到 7 月前
        1
  •  2
  •   Remo H. Jansen    7 月前

    条件类型 typeof multiple extends true 总是 false 这是因为 boolean extends true boolean extends false 也总是假的。看看这个:

    type Value1 = typeof multiple extends true ? never : 'YES';
    type Value2 = typeof multiple extends false ? never : 'YES';
    type Value3 = boolean extends true ? never : 'YES';
    type Value4 = boolean extends false ? never : 'YES';
    type Check = 'YES' & Value1 & Value2 & Value3 & Value4; // YES
    

    全部 Value1 , Value2 , Value3 Value4 是类型 'Yes' 这是可以证明的,因为所有这些类型的并集只有一个(字符串文字)类型 “是” .

    您可以使用联合类型修复它 true | false 而不是 boolean .

    type Value<T> = T extends true ? string[] : string;
    
    const func = (
      multiple: true | false
    ) => {
    
      if (multiple) {
        const foo: Value<typeof multiple> = ['string']
      } else {
        const bar: Value<typeof multiple> = 'string'
      }
    }