Typescript error for "property does not exist', when it clearly does.

I have some objects (named program' in code) in an array which I am iterating through, and reading program.programSecTitle of an object, which is string type. Typescript is showing error saying it does not exist, even though it shows that property name in the object type itself on hovering. It is working fine in the UI, i.e. program.programSecTitle is visible in the UI without any errors. But just in the vscode its showing error. I tried reopening vscode, restarting ts server, reloading vscode window but none worked.
3 Replies
Alejo
Alejo2y ago
Does it work if you do "programSecTitle" in program && instead of program.programSecTitle &&?
~Abhinav
~Abhinav2y ago
oh yes it worked, weird. Can you please help me understand why this solution works but program.programSecTitle && and program["programSecTitle] && did not?
Alejo
Alejo2y ago
The way Typescript works, it prevents you from calling properties that may not exist in an object, not existing is not the same as being undefined for Typescript In your case, what seems to be happening is that this interface/type is an Discriminating Union type, something along the lines of
type A = {
a: string;
b: string;
c: string;
}
type B = {
a: string;
b: string;
c: string;
programSecTitle: string;
}
type C = A | B
type A = {
a: string;
b: string;
c: string;
}
type B = {
a: string;
b: string;
c: string;
programSecTitle: string;
}
type C = A | B
You can read more about it here: https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html Because of this, Typescript cannot guarantee that programSecTitle is a field in type C, since it may not exist in type A, checking for "programSecTitle" in program narrows down the type to B and now typescript can guarantee that property exists
Want results from more Discord servers?
Add your server