介绍
与javascript区别
ts 具有强类型校验,虽然js提供了很多String,Number,Object等基础类型,但js未对其做类型校验。
使用ts 最大的好处在于它可以指出那些未达到预期的代码段,减少基本bug的产生
类型系统 type-system
如下代码中,ts实现了对helloWorld的自动类型定义,即 string 类型;string是type-system中的一个基础类型
let helloWorld = "Hello World";
// ^ = let helloWorld: string
类型定义
我们可以使用很多种方式去定义我们的变量。但总有些变量非常难以被自动定义类型。
例如:
interface User {
name: string;
id: number;
}
const user:User = {
name: "Hayes",
id: 0,
};
定义类型有两种方式:
- Unions 联合式
- Generics 泛型
Unions 联合式
举例:
type MyBool = true | false;
type WindowStates = "open" | "closed" | "minimized";
type LockStates = "locked" | "unlocked";
type OddNumbersUnderTen = 1 | 3 | 5 | 7 | 9;
function getLength(obj: string | string[]) {
return obj.length;
}
泛型
举例:
type StringArray = Array<string>;
type NumberArray = Array<number>;
type ObjectWithNameArray = Array<{ name: string }>;
interface Backpack<Type> {
add: (obj: Type) => void;
get: () => Type;
}
// This line is a shortcut to tell TypeScript there is a
// constant called `backpack`, and to not worry about where it came from.
declare const backpack: Backpack<string>;
// object is a string, because we declared it above as the variable part of Backpack.
const object = backpack.get();
// Since the backpack variable is a string, you can't pass a number to the add function.
backpack.add(23);
Argument of type 'number' is not assignable to parameter of type 'string'.
结构类型体系
即:结构相同的,虽不是同一个类型(interface、type)的变量,只要结构相同,也可相互使用
demo1
interface Point {
x: number;
y: number;
}
function printPoint(p: Point) {
console.log(`${p.x}, ${p.y}`);
}
// prints "12, 26"
const point = { x: 12, y: 26 };
printPoint(point);
demo2
class VirtualPoint {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
const newVPoint = new VirtualPoint(13, 56);
printPoint(newVPoint); // prints "13, 56"