【问题标题】:Conditional parameter type in TypeScriptTypeScript 中的条件参数类型
【发布时间】:2020-07-08 22:59:32
【问题描述】:

我这里有这个函数,第一个参数类型取决于第二个参数是真还是假

所以如果 userExists 为真,数据应该是一个字符串,否则是一个数字。但我一直看到错误。

谁能帮忙解决我哪里出错了?

type DataType<T> = T extends boolean ? string : number

const makeUsername = async <T extends boolean>({
  data,
  userExists,
}: {
  data: DataType<T>,
  userExists: T
}) => {

  if (userExists) {
    // data type should be string
  } else {
    // data type should be number
  }
}

【问题讨论】:

    标签: typescript generics types conditional-statements


    【解决方案1】:

    看起来,你正在尝试构建类似的东西:

    type StringOrNumber<T extends boolean> = T extends true ? string : number
    

    但这不会用于流量分析。所以在if 块中,你不会得到正确的类型推断。

    function makeUsername<T extends boolean>({ data, userExists }: { data: StringOrNumber<T>; userExists: T }): any {
      if (userExists) {
        // But data here is still StringOrNumber<T>. You have to cast it manually.
        const dataStr = data as string;
      } else {
        const dataNum = data as number;
      }
    }
    
    // While on call side it works well
    makeUsername({data: '12', userExists: true}) // ok
    makeUsername({data: 12, userExists: true}) // error
    

    但可能函数重载更适合这里:

    function makeUsername({ data, userExists }: { data: string; userExists: true }): any;
    function makeUsername({ data, userExists }: { data: number; userExists: false }): any;
    function makeUsername({ data, userExists }: { data: string | number; userExists: boolean }): any {     
      if (userExists) {
        // Here you have to cast types anyway...
        const dataStr = data as string;
      } else {
        const dataNum = data as number;
      }
    }
    
    // But on call side, this will also works as expected.
    makeUsername({ data: 'kyo', userExists: true }) // ok
    makeUsername({ data: 'kyo', userExists: false }); // error
    

    【讨论】:

      猜你喜欢
      • 2020-11-10
      • 2020-10-27
      • 2020-03-29
      • 2023-03-28
      • 2020-01-15
      • 2023-01-25
      • 2018-10-20
      • 1970-01-01
      • 2019-02-07
      相关资源
      最近更新 更多