const type p1 = { a: number, b: string }
const type p3 = { a: string }
const type p4 = p1 | p3
let sample: p4 = { a: '123', b: '123' }
function checkP3(obj: p4): obj is p3 {
return typeof (<p3>obj).a === 'string'
}
function functionTest(obj: p4) {
if ('b' in obj) {
// Uncaught TypeError: obj.a.toFixed is not a function
obj.a.toFixed() //<- This now does not throw an error
} else {
}
}
functionTest(sample)
What is the reason behind the absence of an error when initializing the sample variable? User-Defined Type Guards