Closed
Description
TypeScript Version: 2.8.1
Search Terms:
union complex types
Code
interface IOne{
stringOne: string;
numberOne: number;
}
interface ITwo{
stringTwo: string;
numberTwo: number;
}
type IEitherOr = IOne | ITwo;
var itemThree: IEitherOr = {
numberOne: 42343,
stringOne: "",
numberTwo: "sdfsd"
}
Expected behavior:
This should throw an error.
IMHO I think that there are 3 issues here.
- First off I was surprised that
numberTwo
was allowed AT ALL. I think that the type should be eitherIOne
ORITwo
, not a mix of the two. - If we do allowed mixed types (which I don't think we should) then surely if there are any properties for
ITwo
we should require all of them. This should throw an error unless we have specified bothnumberTwo
andstringTwo
- lastly it's not even type checking
numberTwo
. It is typed as a number but it's fine with a string.
Actual behavior:
The compiler is fine with this!
Playground Link:
Link
Work Around:
You can enforce proper type checking on the secondary mixed type like this:
type IFixedEitherOr =
( IOne & Partial<ITwo> )
|
( ITwo & Partial<IOne> );
var itemFour: IFixedEitherOr = {
numberOne: 42343,
stringOne: "",
numberTwo: "dfgdf" // this errors
}
The code above correctly fails to compile.