Skip to main content

ts基础

· 6 min read
ayanami

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

  1. 取消 tsconfig.json 中的 sourceMap(源代码映射)的注释
  2. 配置 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 的接口

泛型 Generic 基本同 java 泛型

// 泛型示例
function echo<T extends string | null>(value: T): T {
return value;
}
echo("1");

keyof 关键字

class Store<T> {
protected _items: T[] = [];
constructor(items: T[]) {
this._items = items;
}
addItem(item: T) {
this._items.push(item);
}
// NOTE: if property is not present in T, it will return undefined. So use keyof T to make sure property is present in T
find(property: keyof T, value: unknown): T | undefined {
return this._items.find((item) => item[property] === value);
}
}

type mapping

// type readOnlyProduct = Readonly<Product>;
type readOnlyProduct = {
readonly [P in keyof Product]: Product[P];
};
type ReadOnly<T> = {
readonly [P in keyof T]: T[P];
};
type Optional<T> = {
[P in keyof T]?: T[P];
};
type Nullable<T> = {
[P in keyof T]: T[P] | null;
};

decorators

框架:内置 decorator,修改一个类的属性

类似类的继承

function decorator(constructor: Function) {
console.log("decorator called");
constructor.prototype.myID = new Date().getTime();
constructor.prototype.someFunction = () => {
console.log("someFunction called");
};
}
@decorator
class MyClass {}

class decorator

type Option = {
selection: string;
};
// NOTE: decorator factory
function paramDecorator(op: Option) {
return (constructor: Function) => {
console.log(`decorator with ${op.selection} called`);
constructor.prototype.profile = op;
constructor.prototype.myID = new Date().getTime();
};
}
@paramDecorator({ selection: "some string" })
class MyClass {}

method decorator:作用一般是增强某个方法

function Log(target: any, methodName: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value as Function;
descriptor.value = function (...args: any) {
console.log("Before");
originalMethod.call(this, ...args);
console.log("After");
};
}
class Person {
@Log
say(message: string) {
console.log(message);
}
}
let person = new Person();
person.say("Hello");

module

import and export

wildcard import

import * as Shapes from "./shapes";

use JSDoc to add basic type checking in js

/**
* the description of function
* @param {string} str - the description of str
* @returns {void}
*/
function test(str) {
console.log("test " + str);
}

也可以使用 .d.ts 声明文件

Loading Comments...