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 ? :(