ts基础
· 6 min read
ts: 带静态类型的 js
配置 ts
tsc --init
tsconfig.json
重要配置
{
"compilerOptions": {
"target": "es2016", // 指定编译器
<!--truncate-->
"module": "commonjs",
"rootDir": "./",
......
"outDir": "./", // 编译完成的js文件位置
"removeComments": true,
"noEmitOnError": true,
}
tsc 默认行为是编译 root 下面的所有.ts 文件,如果上面改了 tsconfig.json,编译 rootDir
只需要tsc即可
debug ts
- 取消 tsconfig.json 中的 sourceMap(源代码映射)的注释
- 配置 debug 里面 launch.json,注意
tsc: build如果开了中文包需要改成tsc: 构建(逆天)
ts 的优点
限定方法之后可以减少错误
还可以方便的和 IntelliSense 集成,对不同类型的对象提供不同的代码补全
打开
{
"compilerOptions": {
"target": "ES5",
"module": "CommonJS",
"outDir": "out",
"rootDir": "./src",
"sourceMap": true,
"noImplicitAny": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noUnusedLocals": true
}
}
ts 支持对函数参数个数的检查,也支持默认值
ts 的对象
let s1: {
readonly id: number;
name: string;
enroll: (date: Date) => void;
} = {
id: 1,
name: "Ayanami",
enroll: (date: Date) => {
console.log(date);
},
};
使用 tpye alias
let s1: student = {
id: 1,
name: "Ayanami",
enroll: (date: Date) => {
console.log(date);
},
};
type student = {
readonly id: number;
name: string;
enroll: (date: Date) => void;
};
type narrowing
function LogWeight(weight: number | string) {
if (typeof weight === "number") {
console.log(weight.toString() + "kg");
}
if (typeof weight === "string") {
console.log(weight);
}
}
type intersection
type dragble = {
drag: () => void;
};
type resizeble = {
resize: () => void;
};
type UIwidget = dragble & resizeble;
let textbox: UIwidget = {
drag: () => {},
resize: () => {},
};
type 也可以是指定的值(literal type)
type percent = 50 | 100;
type Metric = "cm" | "inch";
ts null/undefined
null 不能直接传递给类似 string 类型的参数, 需要用到的时候要用交集
function f(str: string | null): void {
if (str) console.log(str);
else {
console.log("Null");
}
}
可选运算符?
type user = { name: string; age: number };
type disgust = user | null | undefined;
function handle(dis: disgust): void {
console.log(dis?.name); // 只有当dis不是null和undefined的时候才会执行.
}
type assert
用于向编译器表明“我比你更懂它是什么类型”和得到对应类型的方法 补全
let phone = document.getElementById("phone") as HTMLInputElement;
console.log(phone.value);
using 'unknown' type && type narrowing instead of using 'any' type
instanceof 的使用
OOP
class account {
readonly id: number;
private _balance: number;
name: string;
constructor(id: number, balance: number, name: string) {
this.id = id;
this._balance = balance;
this.name = name;
}
withdraw(amount: number) {
this._balance -= amount;
}
getBalance() {
return this._balance;
}
}
let acc: account = new accout(1, 100, "Ayanami");
acc.withdraw(10);
console.log(acc instanceof account);
// 或者
class account {
constructor(
public readonly: number,
private _balance: number,
public name: string
) {}
withdraw(amount: number): void {
this._balance -= amount;
}
getBalance(): number {
return this._balance;
}
}
let acc: account = new account(1, 100, "Ayanami");
acc.withdraw(10);
console.log(acc instanceof account);
// 更好的getBalance
get balance():{
return this._balance;
}
}
// 然后外面可以直接
let b = acc.balance; // 可以
acc.balancew = 2; // 不行
Index signature
class seatsAssign {
[seats: string]: string;
}
let s = new seatsAssign();
s["A1"] = "Ayanami";
s["A2"] = "Nimi Sora";
静态成员:类似 java 的语法
继承语法 class A extends B
重载语法 override function()
抽象类 abstract class A, 抽象方法也是前面加 abstract
接口 interface 基本同 java 的接口