2014-11-05 23:12:29 +01:00
|
|
|
//// [typeGuardsDefeat.ts]
|
|
|
|
// Also note that it is possible to defeat a type guard by calling a function that changes the
|
|
|
|
// type of the guarded variable.
|
|
|
|
function foo(x: number | string) {
|
|
|
|
function f() {
|
|
|
|
x = 10;
|
|
|
|
}
|
|
|
|
if (typeof x === "string") {
|
|
|
|
f();
|
|
|
|
return x.length; // string
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
return x++; // number
|
|
|
|
}
|
|
|
|
}
|
|
|
|
function foo2(x: number | string) {
|
|
|
|
if (typeof x === "string") {
|
|
|
|
return x.length; // string
|
|
|
|
}
|
|
|
|
else {
|
2014-11-14 19:42:31 +01:00
|
|
|
var f = function () {
|
|
|
|
return x * x;
|
|
|
|
};
|
2014-11-05 23:12:29 +01:00
|
|
|
}
|
2014-11-14 19:42:31 +01:00
|
|
|
x = "hello";
|
|
|
|
f();
|
2014-11-05 23:12:29 +01:00
|
|
|
}
|
|
|
|
function foo3(x: number | string) {
|
|
|
|
if (typeof x === "string") {
|
|
|
|
return x.length; // string
|
|
|
|
}
|
|
|
|
else {
|
2014-11-14 19:42:31 +01:00
|
|
|
var f = () => x * x;
|
2014-11-05 23:12:29 +01:00
|
|
|
}
|
2014-11-14 19:42:31 +01:00
|
|
|
x = "hello";
|
|
|
|
f();
|
|
|
|
}
|
|
|
|
|
2014-11-05 23:12:29 +01:00
|
|
|
|
|
|
|
//// [typeGuardsDefeat.js]
|
|
|
|
// Also note that it is possible to defeat a type guard by calling a function that changes the
|
|
|
|
// type of the guarded variable.
|
|
|
|
function foo(x) {
|
|
|
|
function f() {
|
|
|
|
x = 10;
|
|
|
|
}
|
|
|
|
if (typeof x === "string") {
|
|
|
|
f();
|
|
|
|
return x.length; // string
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
return x++; // number
|
|
|
|
}
|
|
|
|
}
|
|
|
|
function foo2(x) {
|
|
|
|
if (typeof x === "string") {
|
|
|
|
return x.length; // string
|
|
|
|
}
|
|
|
|
else {
|
2014-11-14 19:42:31 +01:00
|
|
|
var f = function () {
|
|
|
|
return x * x;
|
|
|
|
};
|
2014-11-05 23:12:29 +01:00
|
|
|
}
|
2014-11-14 19:42:31 +01:00
|
|
|
x = "hello";
|
|
|
|
f();
|
2014-11-05 23:12:29 +01:00
|
|
|
}
|
|
|
|
function foo3(x) {
|
|
|
|
if (typeof x === "string") {
|
|
|
|
return x.length; // string
|
|
|
|
}
|
|
|
|
else {
|
2014-11-14 19:42:31 +01:00
|
|
|
var f = function () { return x * x; };
|
2014-11-05 23:12:29 +01:00
|
|
|
}
|
2014-11-14 19:42:31 +01:00
|
|
|
x = "hello";
|
|
|
|
f();
|
2014-11-05 23:12:29 +01:00
|
|
|
}
|