#1---接口
interface User {
name: string;
id: number;
}
const user: User = {
username: "Hayes",
id: 0,
};
#2---类
class UserAccount {
name: string;
id: number;
constructor(name: string, id: number) {
this.name = name;
this.id = id;
}
}
const user: User = new UserAccount("Murphy", 1);
#3---函数
function getAdminUser(): User {
//...
}
function deleteUser(user: User) {
// ...
}
#4---Composing Types:unions
type WindowStates = "open" | "closed" | "minimized";
type LockStates = "locked" | "unlocked";
type OddNumbersUnderTen = 1 | 3 | 5 | 7 | 9;
----处理不同类型的函数
function getLength(obj: string | string[]) {
return obj.length;
}
#5---判断类型
Type Predicate
string typeof s === "string"
number typeof n === "number"
boolean typeof b === "boolean"
undefined typeof undefined === "undefined"
function typeof f === "function"
array Array.isArray(a)
-----判断类型的应用
function wrapInArray(obj: string | string[]) {
if (typeof obj === "string") {
return [obj];
// ^ = (parameter) obj: string
} else {
return obj;
}
}
#6---Composing Types:Generics
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();
// Due to backpack variable being a string, you cannot pass a number to the add function
backpack.add(23);
#7---Structural Type System
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);
const point3 = { x: 12, y: 26, z: 89 };
printPoint(point3); // prints "12, 26"
const rect = { x: 33, y: 3, 30, height: 80 };
printPoint(rect); // prints "33, 3"
const color = { hex: "#187ABF" };
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"
// Declare a tuple type
let x: [string, number];
// Initialize it
x = ["hello", 10]; // OK
// OK
console.log(x[0].substring(1));
#8---枚举类型、enum Color
enum Color {
Red,
Green,
Blue,
}
let c: Color = Color.Green;
{
Red = 1,
Green = 2,
Blue = 4,
}
let c: Color = Color.Green;
enum Color {
Red = 1,
Green,
Blue,
}
let colorName: string = Color[2];
// Displays 'Green'
console.log(colorName);