https://www.tslang.cn/docs/home.html
变量
// 布尔
let isDone: boolean = false;
// 数字
let decLiteral: number = 6;
let hexLiteral: number = 0xf00d;
let binaryLiteral: number = 0b1010;
let octalLiteral: number = 0o744;
// 字符串
let fname: string = "bob";
let sentence: string = `Hello, my name is ${fname}.`;
// 数组
let list1: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3];
// 元组
let x: [string, number];
x = ["hello", 10]; // OK
// x = [10, "hello"]; // Error
// 枚举
enum Color {
Red,
Green,
Blue,
}
let c: Color = Color.Green;
console.log(c); //1
let colorName: string = Color[2];
console.log(colorName); //Blue
// Any
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // ok
let list: any[] = [1, true, "free"];
list[1] = 100;
let some; //声明时未指定类型时默认any
some = 1;
some = "a";
// void
function warnUser(): void {
console.log("This is my warning message");
}
// undefined null 可以赋给其他类型变量
let u: undefined = undefined;
let n: null = null;
// never
function error(message: string): never {
throw new Error(message);
}
function infiniteLoop(): never {
while (true) {}
}
// Object
let o: object = {};
// 类型断言 规避类型检查
let someValue: any = "this is a string";
let strLength1: number = (<string>someValue).length;
let strLength: number = (someValue as string).length;
// 类型推断
let somea = 1; //类型自动推断为number
// somea = "1"; //报错
//联合类型
let star: string | number = "1";
star = 1;
// 别名
type mytype = string | number;
type Eventname = "Click" | "scroll";
接口
// 对象接口
interface person {
name: string;
age: number;
readonly gender: string; //只读属性
like?: string; //可选属性
[propName: string]: any; //任意属性
}
// 索引
interface numberArr {
[index: number]: number;
}
// 函数接口
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc;
mySearch = function (src, sub) {
let result = src.search(sub);
return result > -1;
};
// 类接口
interface ClockInterface {
currentTime: Date;
setTime(d: Date): void;
}
class Clock implements ClockInterface {
currentTime: Date;
setTime(d: Date) {
this.currentTime = d;
}
constructor(h: number, m: number) {
this.currentTime = new Date();
}
}
// 接口继承
interface Shape {
color: string;
}
interface PenStroke {
penWidth: number;
}
interface Square extends Shape, PenStroke {
sideLength: number;
}
let square = <Square>{};
square.color = "blue";
square.sideLength = 10;
square.penWidth = 5.0;
面向对象
class Animal {
// 继承类可以访问
protected name: string;
// 构造函数里可以使用 public name 来简写
constructor(name: string) {
this.name = name;
}
move(distanceInMeters: number = 0) {
console.log(`Animal moved ${distanceInMeters}m.`);
}
static isAnimal(animal: object): boolean {
return animal instanceof Animal;
}
}
//继承
class Dog extends Animal {
// 私有属性,只读
private readonly color: string = "blackack";
constructor(name: string) {
super(name);
}
move(distanceInMeters: number = 0) {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
bark() {
console.log(`${this.color} ${this.name}: Woof! Woof!`);
}
}
const dog = new Dog("dog");
dog.move(10);
dog.bark();
console.log(Animal.isAnimal(dog));
//抽象类
abstract class absAnimal {
abstract makeSound(): void; // 必须在派生类中实现
move(): void {
console.log("roaming the earch...");
}
}
函数
//可选参数
function buildName1(firstName: string, lastName?: string) {
if (lastName) return firstName + " " + lastName;
else return firstName;
}
//默认参数
function buildName2(firstName: string, lastName = "Smith") {
if (lastName) return firstName + " " + lastName;
else return firstName;
}
//收集参数
function buildName3(firstName: string, ...restOfName: string[]) {
return firstName + " " + restOfName.join(" ");
}
//函数重载
function getInfo(name: string): void;
function getInfo(age: number): void;
function getInfo(str: any): void {
if (typeof str == "string") {
console.log("名字:", str);
}
if (typeof str == "number") {
console.log("年龄", str);
}
}
泛型
function createArray<T>(value: T, length: number): Array<T> {
let result: T[] = [];
for (let i = 0; i < length; i++) {
result[i] = value;
}
return result;
}
let a = createArray([1, 2, 3], 3);
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}
let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function (x, y) {
return x + y;
};