13 TypeScript
(This is an optional minor lab). TypeScript is a new programming language built by Microsoft that is defined by a desugaring to JavaScript. The TypeScript language specification has the following description of subtyping method parameter lists:
“for parameter positions that are present in both signatures, each parameter type in N is a subtype or supertype of the corresponding parameter type in M, and the result type of M is Void, or the result type of N is a subtype of that of M.”
(Page 51, http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf)
Read that section to understand the context of the excerpt above.
Is TypeScript’s method argument subtyping co-variant, contra-variant, or something else? What about method return type subtyping?
This rule for subtyping is unsound: it allows a type-checked program to “lie” about the return type of a function. Fill in the TypeScript program at
that demonstrates the unsoundness via this rule, and understand where in the program the subtyping rule above is used.
Is this rule a good idea?
Update: One solution is here, copied below (spoilers, so scroll down):
class Common { } |
class A extends Common { |
x: string; |
} |
class B extends Common { |
x: number; |
} |
|
function g(h : (Common) => number) { |
var message = new A; |
message.x = "This is not a number at all"; |
return h(message); |
} |
|
function getXFromB(b : B) : number { |
return b.x; |
} |
|
function f(): number { |
return g(getXFromB); |
} |
|
var make_this_a_string : number = f(); |
alert("Not actually a number: " + make_this_a_string); |
The unsound subtyping rule is used at the call g(getXFromB), where the argument type B from getXFromB is compared covariantly to Common. The sound version of the rule would ask Common <: B, but TypeScript asks Common <: B or B <: Common. Since the second is true, the body of g is free to lie to getXFromB and provide an A-typed value rather than a B-typed one.
There’s a blog post about this behavior at
https://typescript.codeplex.com/wikipage?title=Type%20Compatibility%20in%20TypeScript