【问题标题】:Fix a compile error when comparing a T[keyof T] and a string in Typescript修复比较 T[keyof T] 和 Typescript 中的字符串时的编译错误
【发布时间】:2021-05-31 12:03:52
【问题描述】:

当我比较 T[keyof T]string(其中 T 是泛型)时,我得到了这个错误。

此条件将始终返回 'false',因为类型 'T[keyof T]' 和 'string' 没有重叠。ts(2367)

function descendingComparator<T>(a: T, b: T, orderBy: keyof T) {
  if ((a[orderBy] === 'abc') && (b[orderBy] === 'def')) {
    // Error. This condition will always return 'false' since the types 'T[keyof T]' and 'string' have no overlap.ts(2367)
    return 1
  }
  return 0;
}
const x = {name: 'abc'}
const y = {name: 'def'}
descendingComparator(x, y, 'name')

如何修复这个编译错误?谢谢。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    解决此问题的一种方法:

    function descendingComparator<T>(a: T, b: T, orderBy: keyof T) {
      if (((a[orderBy] as string) === 'abc') && ((b[orderBy] as string) === 'def')) {
        // Error. This condition will always return 'false' since the types 'T[keyof T]' and 'string' have no overlap.ts(2367)
        return 1
      }
      return 0;
    }
    const x = {name: 'abc'}
    const y = {name: 'def'}
    descendingComparator(x, y, 'name')
    

    更好的方法是:

    function descendingComparator<T>(a: T, b: T, orderBy: keyof T) {
      if ((typeof a[orderBy] === 'string' && a[orderBy] === 'abc') && (typeof b[orderBy] === 'string' && b[orderBy] === 'def')) {
        // Error. This condition will always return 'false' since the types 'T[keyof T]' and 'string' have no overlap.ts(2367)
        return 1
      }
      return 0;
    }
    const x = {name: 'abc'}
    const y = {name: 'def'}
    descendingComparator(x, y, 'name')
    

    【讨论】:

      猜你喜欢
      • 2021-05-21
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-20
      • 1970-01-01
      相关资源
      最近更新 更多