Consider a scenario where there are 2 types with the same property name but different data types:
type A = {
myProperty:string
}
type B = {
myProperty:number
}
If both types are extended using an interface, an error is expected:
interface C extends A, B {}
Interface 'C' cannot simultaneously extend types 'A' and 'B'.
Named property 'myProperty' of types 'A' and 'B' are not identical.
However, when a type is used to extend both types, no exception occurs. In this case, what will be the resulting data type of myProperty
? Is there a method to verify the resulting data type?
type C = A & B; // no error
If C is declared as a type, it is not possible to assign a value (string or number) to myProperty
. How can this situation be best managed?
function F(myParameter:C) {
console.log(myParameter);
}
F({myProperty: 90});
(property) myProperty: never
Type 'number' is not assignable to type 'never'.ts(2322)
index.ts(3, 3): The expected type comes from property 'myProperty' which is declared here on type 'C'
The same error occurs if the function is called as F({myProperty: 'test data'});
.
Interactive example: https://codesandbox.io/s/typescript-playground-export-forked-dglbq5?file=/index.ts