Boolean
let isDone: boolean = false;
Number
所有的 number 都是浮点数, 同时支持 hexadecimal 和 decimal 这两种 literal 的写法
let decimal: number = 6;
let hex: number = 0xf00d;
String
let color: string = "blue";
color = 'red';
let fullName: string = `Bob Bobbington`;
let age: number = 37;
let sentence: string = `Hello, my name is ${ fullName }.
Array
let list: number[] = [1, 2, 3]
// or
let list: Array<number> = [1, 2, 3]
Tuple
是一个元素数量固定的 array
元素的类型可以不一样
let x: [string, number]; // delcare a tuple
x = ['hello', 10]; // initialize it
x = [10, 'hello']; // initialize it incorrectly
// 超出下标范围的话, 使用 union type
x[3] = "world"; // OK, 'string' can be assigned to 'string | number'
console.log(x[5].toString()); // OK, 'string' and 'number' both have 'toString'
x[6] = true; // Error, 'boolean' isn't 'string | number'
Enum
enum Color {Red, Green, Bulue};
// js: { '0': 'Red', '1': 'Green', '2': 'Blue', Red: 0, Green: 1, Blue: 2 }
// 默认从 0 开始递增, 可以给初始值来改变这个行为
enum Color {Red = 1, Green, Blue};
// 当然也可以全部自由赋值
enum Color {Red = 1, Green = 2, Blue = 4};
// 看最上面的 js
enum Color {Red = 1, Green, Blue};
let colorName: string = Color[2];
console.log(colorName); // Displays 'Green' as its value is 2 above
Any
用 any
来给不能确定类型的变量
和 Object
的区别:
let notSure: any = 4;
notSure.ifItExists(); // okay, ifItExists might exist at runtime
notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check)
let prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.
Void
就是 null
和 undefined
, 给一个更统一的称呼而已
function warnUser(): void {
console.log("This is my warning message");
}
let unusable: void = undefined;
Null and Undefined
Null and Undefined
// Not much else we can assign to these variables!
// 是的, null 和 undefined 都有自己的类型名字
let u: undefined = undefined;
let n: null = null;
默认来说, null
和 undefined
是其他类型的子类型, 因此可以赋值给其他类型的变量,
如果想改变这个默认行为的话, 那么可以使用 --strictNullChecks
Never
the type of never occur
never 是所有类型的子类, 它没有子类
// Function returning never must have unreachable end point
function error(message: string): never {
throw new Error(message);
}
// Inferred return type is never
function fail() {
return error("Something failed");
}
// Function returning never must have unreachable end point
function infiniteLoop(): never {
while (true) {
}
}
Object
non-primitive type, 也就是除了 number, string, boolean, symbol, null, undefined 的其他类型
declare function create(o: object | null): void;
create({ prop: 0 }); // OK
create(null); // OK
create(42); // Error
create("string"); // Error
create(false); // Error
create(undefined); // Error
Type assertions
ts 会自动推断变量的类型
如果自己明确地知道类型, 想要编译器闭嘴的时候, 可以使用 type assertions
有两种写法:
// 尖括号
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
// as, 写 JSX 的时候只能写这种
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;