// Succeeds if `node_modules/asdf/index.js` exists
import { x } from "asdf";
let x; // 隐式 'any'
let y = []; // 隐式 'any[]'
let z: any; // 显式 'any'.
let x;
// 你仍然可以给'x'赋值任何你需要的任何值。
x = () => 42;
// 在刚赋值后,TypeScript 2.1 知道'x'的类型是'() => number'。
let y = x();
// 感谢,现在它会告诉你,你不能添加一个数字到一个函数!
console.log(x + y);
// ~~~~~
// 错误!运算符 '+' 不能应用于类型`() => number`和'number'。
// TypeScript仍然允许你给'x'赋值你需要的任何值。
x = "Hello world!";
// 并且现在它也知道'x'是'string'类型的!
x.toLowerCase();
function f1() {
let x = [];
x.push(5);
x[1] = "hello";
x.unshift(true);
return x; // (string | number | boolean)[]
}
function f2() {
let x = null;
if (cond()) {
x = [];
while (cond()) {
x.push("hello");
}
}
return x; // string[] | null
}
function f3() {
let x = []; // 错误:当变量'x'类型无法确定时,它隐式具有'any[]'类型。
x.push(5);
function g() {
x; // 错误:变量'x'隐式具有'any【】'类型。
}
}
const c1 = 1; // Type 1
const c2 = c1; // Type 1
const c3 = "abc"; // Type "abc"
const c4 = true; // Type true
const c5 = cond ? 1 : "abc"; // Type 1 | "abc"
let v1 = 1; // Type number
let v2 = c2; // Type number
let v3 = c3; // Type string
let v4 = c4; // Type boolean
let v5 = c5; // Type number | string
const c1 = "hello"; // Widening type "hello"
let v1 = c1; // Type string
const c2: "hello" = "hello"; // Type "hello"
let v2 = c2; // Type "hello"
class Base {
x: number;
constructor() {
// 返回一个除“this”之外的新对象
return {
x: 1,
};
}
}
class Derived extends Base {
constructor() {
super();
this.x = 2;
}
}
var Derived = (function (_super) {
__extends(Derived, _super);
function Derived() {
var _this = _super.call(this) || this;
_this.x = 2;
return _this;
}
return Derived;
}(Base));