Upon finishing an article discussing conditional types in TypeScript located at:
I have attempted to implement a conditional type in the following function:
function convertToIsoString<T extends number|undefined>(
timestamp:T
): T extends number ? string : undefined {
if (typeof timestamp === 'number') {
return (new Date(timestamp)).toISOString() // encountered error [1]
}
return undefined // encountered error [2]
}
const myTimestamp:number|undefined = 1570081092848
console.log(convertToIsoString(myTimestamp)) // 2019-10-03T05:38:12.848Z
The code above generated 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'
Frustrated by my confusion, I decided to test the code from the mentioned article:
function manipulateText<T extends string | null>(
text: T
): T extends string ? string : null {
return text && text.replace(/f/g, 'p') // encountered error [3]
}
const possibleText: string | null = 'foo'
console.log(manipulateText(possibleText).toUpperCase()) // POO
To my surprise, I faced a similar issue:
// [3] Type 'string' is not assignable to type 'T extends string ? string : null'
What could I be overlooking? :(