You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
interface IFoo {
foo: string;
}
interface IBar {
bar: string;
}
class Foo implements IFoo{
foo: string;
}
class Bar implements IBar{
bar: string;
newProperty: string;
}
let x:Foo|Bar = new Bar();
let y:IFoo = x as IFoo; // Works as expected, no errors
let u:Foo|Bar = new Bar();
let z:IBar = u as IBar; //Does not work IFF Bar contains more properties than IBar
We have a situation where a property is a union of several classes, and we would like to cast it to the correct interface in different situations. However this does not seem to work if the class has properties that is not present on the implemented interface. Playground link
The text was updated successfully, but these errors were encountered:
Thanks for your input! However I think I have not made my intentions clear enough, so I will clarify.
When you make a class that implements an interface, you are allowed to add more properties without error, as long as you uphold your contract with the interface.
What I am trying to do is this (just with an added union)
interface IBar {
bar: string;
}
class Bar implements IBar{
bar: string;
newProperty: string;
}
let u: Bar = new Bar();
let z: IBar = u as IBar;
This does not produce an error in Typescript, and I assume this is because the class Bar implements the interface IBar, therefore it is guaranteed that casting an instance of bar to IBar should not break the contract of the IBar interface.
This allows us to restrict our knowledge of an instance to only the information that we need in the current context.
I want to use this principle with unions. So instead of knowing that the instance is a Bar class, I know that it is either a Bar instance or a Foo instance. I do not want to cast directly to Foo or Bar, because I only need to know the interfaces they implement, so instead I want to cast to IFoo or IBar, because I know for a fact which it is during execution.
We have a situation where a property is a union of several classes, and we would like to cast it to the correct interface in different situations. However this does not seem to work if the class has properties that is not present on the implemented interface. Playground link
The text was updated successfully, but these errors were encountered: