打字稿条件类型不起作用

时间:2019-10-03 06:00:15

标签: typescript

在以下位置阅读了有关打字稿的条件类型的文章: https://artsy.github.io/blog/2018/11/21/conditional-types-in-typescript/

我正在尝试将条件类型应用于以下功能:

function getIsoStringFromDatestamp<T extends number|undefined>(
  receivedAt:T
): T extends number ? string : undefined {
  if (typeof receivedAt === 'number') {
    return (new Date(receivedAt)).toISOString() // typeError [1]
  }
  return undefined // typeError [2]
}

const dateStamp:number|undefined = 1570081092848
console.log(getIsoStringFromDatestamp(dateStamp))  // 2019-10-03T05:38:12.848Z

上面的代码具有以下类型错误:

// [1] Type 'string' is not assignable to type 'T extends number ? string : undefined'
// [2] Type 'undefined' is not assignable to type 'T extends number ? string : undefined'

根据我的理解,我尝试了文章中的代码:

function process<T extends string | null>(
  text: T
): T extends string ? string : null {
  return text && text.replace(/f/g, 'p') // error [3]
}
const maybeFoo: string | null = 'foo'
console.log(process(maybeFoo).toUpperCase()) // POO

事实证明我也遇到类似的错误:

// [3] Type 'string' is not assignable to type 'T extends string ? string : null'

我想念什么? :(

1 个答案:

答案 0 :(得分:1)

您必须键入返回值任何。如文章(评论部分)所述,这是一个公开问题https://github.com/microsoft/TypeScript/issues/24929

function getIsoStringFromDatestamp<T extends number|undefined>(
  receivedAt:T
): T extends number ? string : undefined {
  if (typeof receivedAt === 'number') {
    return (new Date(receivedAt)).toISOString() as any
  }
  return undefined as any
}

const dateStamp:number|undefined = 1570081092848
console.log(getIsoStringFromDatestamp(dateStamp))