Typescript - Properties with no intersection
You might, eventually, end up with the following typescript code (which runs perfectly fine in javascript btw):
function intersectionExample(intersection: {a: string} | {b: string}) {
if (intersection.a) {//a
console.log(intersection.a); // b
}
}
Which lead to this error on both line a and b:
Error(1): TS2339: Property 'a' does not exist on type
'{ a: string; } | { b: string; }'.
Property 'a' does not exist on type '{ b: string; }'.
So how to tell typescript compiler I’m now what I’m doing?
Just use the in
statement of javascript.
function intersectionExample(intersection: {a: string} | {b: string}) {
if ('a' in intersection) {//a
console.log(intersection.a); // b
}
}
The solution here looks rather easy, although I had to search quite a bit for it.
Actually, due to the sloppiness of javascript I never really had to use the in
statement on my daily work, it was always good enough to simple access the property
and if it’s there work with, like in the first failing example.
Written on March 31, 2020