I have two interfaces.
interface Person {
name: string;
weight: number;
}
interface Dog {
name: string;
mass: number
}
const attribute = isDog ? 'mass' : 'weight';
const player: Person | Dog = "Object with specific type"
if (player[attribute] === 0) return;
I have this error:
TS7053: Element implicitly has an 'any' type because expression of type '"mass" | "weight"' can't be used to index type 'Person | Dog'.
The API can return both Dog or Person and it depends on other parameter. I would like to know what is the best way to tell TS that if player is Person use 'weight' and if the player is Dog use 'mass'. I dont want to use "any" type.
CodePudding user response:
TypeScript is actually helpful here: if, for example, attribute
is "mass"
, but player
is a Person
, then it will be a legitimate error since mass
property doesn't exist on Person
instances.
You avoid this error, you need to change the approach. You could add a runtime check of attribute
actually existing in player
, but I'd argue that you should use the isDog
variable (it's just more logical):
const isDog = "mass" in player;
const mass = isDog ? player.mass : player.weight;
if (mass === 0) return;