0

After reading this article on typescript's conditional type at: https://artsy.github.io/blog/2018/11/21/conditional-types-in-typescript/

I am trying to apply condition type to the following function:

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

the above code has the following type errors:

// [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'

Suspicious at my understanding, I try out the code in the article:

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

it turns out that I am also getting similar error:

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

What am I missing ? :(

0

1 Answer 1

2

You have to typecast the returned value as any. As mentioned in the article(comments section) this is an open issue 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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.