How do I tell TypeScript that two variables have the same type?
I have a few classes that all have the same function with a parameter that takes itself:
class Foo {
takesSelf(x: Foo) {}
}
class Bar {
takesSelf(x: Bar) {}
}
Now I have two variables, of which I know that both are the same type, both are either Foo
or Bar
, the two types will never be mixed. But if I call takesSelf
I get a type error.
const typeA = new Bar() as Foo | Bar;
const typeB = new Bar() as Foo | Bar;
typeA.takesSelf(typeB);
// ^^^^^----- Type 'Foo' is not assignable to type 'Bar'
Which makes sense, because TypeScript doesn't know these two variables will always share the same type.
How can I tell TypeScript these two variables will have the same type, while keeping things type safe?
Here's a playground link with an example and some failed experiments.
from Recent Questions - Stack Overflow https://ift.tt/gWafuGt
https://ift.tt/ln6XjYu
Comments
Post a Comment