I learnt that the
rule for TypeScript’s structural type system is that
x
is compatible withy
ify
has at least the same members asx
This allows an assignment of a variable of a subtype to a variable of a supertype. Is there a way to get a compile-time error regarding that assignment?
interface SuperT {
field: string
}
// an explicitly declared subtype object for a supertype variable generates an error
const super1: SuperT = {field: 'value', extra: 1} // compile-time error: Type '{ field: string; extra: number; }' is not assignable to type 'SuperT'
function subTValue() { return {field: 'value', extra: 1} }
const super2: SuperT = subTValue() // no compile-time error, BUT HOW TO get a compile-time error here?