typescript语法大全

介绍

这是一篇typescript的语法说明书

安装

1
2
npm install -g typescript
tsc hello.ts 编译ts文件

数据类型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// boolean:
let isDone: boolean = false

// number, string, void, null, undefined,any

// union:
let myFavoriateNumber: string | number

// interfaces: 对行为的抽象,而具体如何行动需要由类(classes)去实现(implement)
interface: Person {
name: string;
age?: number; // age是可选属性, 用 ?表示可选
[propName: string]: any; // 允许有任意的属性
readonly id: number // 只读属性
}

// array:
let fibonacci: number[] = [1, 1, 2, 3, 5]

函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function buildName(firstName: string = 'cat', lastName?:string, ...items: any[]):string{
let r: number[] = []
items.forEach(item => r.push(item))
return lastName ? firstName + lastName : firstName
}

// 函数重载
function reverse(x: number): number;
function reverse(x: string): string;
function reverse(x: number | string): number | string {
if (typeof x === 'number') {
return Number(x.toString().split('').reverse().join(''));
} else if (typeof x === 'string') {
return x.split('').reverse().join('');
}
}

类型断言

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
interface Cat {
name: string;
run(): void;
}
interface Fish {
name: string;
swim(): void;
}
function isFish(animal: Cat | Fish) {
// 使用类型断言 "值 as" 的方式解决了联合类型变量只能访问共有属性的问题
if(typeof (animal as Fish).swim === 'function') {
return true;
}
return false;
}
(window as any).foo = 1

声明与导出

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// 声明全局变量
declare var
// 声明全局方法
declare function
// 声明全局类
declare class
// 声明全局枚举类型
declare enum
// 声明(含有子属性的)全局对象
declare namespace
// 声明全局类型
interfacetype
// 导出变量
export
// 导出(含有子属性的)对象
export namespace
// ES6 默认导出
export default
// 导出模块
export = commonjs
// UMD 库声明全局变量
export as namespace
// 扩展全局变量
declare global
// 扩展模块
declare module
/// <reference /> 三斜线指令
// 在引入外部文件的时候,比如jquery,因为ts中在编译过程的时候,需要每个变量进行定义
declare var jQuery: (selector: string) => any
declare namespace JQuery {
function ajax(url: string, settings?: any): void
}

类型别名

1
2
3
type Name = string
type NameResolver = () => string
type NameOrResolver = Name | NameResolver

字符串字面量类型

1
2
3
4
5
6
type EventNames = 'click' | 'scroll' | 'mousemove';
function handleEvent(ele: Element, event: EventNames) {
// do something
}
handleEvent(document.getElementById('hello'), 'scroll'); // 没问题
handleEvent(document.getElementById('world'), 'dblclick'); // 报错,event 不能为 'dblclick'

元祖

1
let tom: [string, number] = ['tom', 25]

枚举

1
2
3
// 默认第一个是0,依次递增加一
enum Days {sun, mon, tue, wed, thr, fir, sat}
enum Days {sun=7, mon=1, tue, wed, thr, fri, sat}

1
2
// 抽象类的抽象方法,继承的类要具体实现
public, private, protect, static, readonly, abstract

接口

1
2
3
4
5
6
7
8
9
10
11
12
// 接口可以继承接口
// 一个类可以实现多个接口
// 接口可以继承类
interface Alarm {
alert():void
}
class Door {}
class SecurityDoor extends Door implements Alarm {
alert() {
console.log('securitydoor')
}
}

泛型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// 在函数内部使用泛型变量的时候,由于事先不知道它是哪种类型,所以不能随意的操作它的属性或方法
// 但是可以通过约束的办法解决这个问题
interface Lengthwise {
length: number;
}

function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}
// 泛型的写法
function createArray<T>(length: number, value: T):Array<T>{
let result: T[] = []
for (let i = 0; i < length; i++) {
result[i] = value
}
return result
}
create<string>(3, 'x')

// 多个类型参数
function swap<T, U>(tuple: [T, U]): [U, T] {
return [tuple[1], tuple[0]];
}

swap([7, 'seven']); // ['seven', 7]
// 泛型接口
nterface CreateArrayFunc<T> {
(length: number, value: T): Array<T>;
}

let createArray: CreateArrayFunc<any>;
createArray = function<T>(length: number, value: T): Array<T> {
let result: T[] = [];
for (let i = 0; i < length; i++) {
result[i] = value;
}
return result;
}

createArray(3, 'x'); // ['x', 'x', 'x']
// 泛型参数的默认类型
function createArray<T = string>(length: number, value: T): Array<T> {
let result: T[] = [];
for (let i = 0; i < length; i++) {
result[i] = value;
}
return result;
}

声明合并

1
2
3
4
5
6
7
8
9
10
// 函数的合并
function reverse(x: number): number;
function reverse(x: string): string;
function reverse(x: number | string): number | string {
if (typeof x === 'number') {
return Number(x.toString().split('').reverse().join(''));
} else if (typeof x === 'string') {
return x.split('').reverse().join('');
}
}

接口的合并

1
2
3
4
5
6
interface Alarm {
price: number;
}
interface Alarm {
weight: number;
}

在react中使用ts的一些准备

  1. 声明png,modules.scss,window等全局对象
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    declare module '*.png' {
    const src: string;
    export default src;
    }

    declare module '*.svg' {
    const content: string;
    export default content;
    }

    declare module '*.module.scss' {
    const classes: { readonly [key: string]: string };
    export default classes;
    }

    interface Window {
    location: Location;
    }
  2. 组件的编写
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    // 函数式组件
    const Home: React.FC<{name: string;}> = (props) => {return <div />}
    // 如果你需要定义defaultProps,那么不要使用React.FC
    const defaultProps = { name: 'woyao' };
    type IProps = { age: number } & typeof defaultProps;
    const Home = (props: IProps ) => { return <div /> }
    // 类组件
    interface IProps {};
    interface IState {};
    const Home extends React.Component<IProps, IState> {
    state: IState = {};
    render(){ return <div />; }
    }
  3. React相关的类型
    1
    2
    3
    4
    5
    6
    7
    /* ReactNode */
    /* 在React中,所有事件(包括FormEvent、KeyboardEvent、MouseEvent等)都是SyntheticEvent的子类型。 */
    /* React.FormEvent */
    /* React.MouseEvent */
    /* React.KeyboardEvent */
    /* React.BaseSyntheticEvent*/
    /* React.SyntheticEvent */

一些高级类型

  • Readonly: 只读类型
    1
    2
    3
    4
    5
    type Readonly<T> = {
    readonly [P in keyof T]: T[P];
    }
    interface IProps = {name: string;};
    const person: Readonly<IProps> = {name: 'woyao' };
  • partial: 将类型定义的所有属性都修改为可选
    1
    2
    3
    4
    5
    type Partial<T> = {
    [P in keyof T]?: T[P];
    }
    interface PersonProps = { name: string; age: number; };
    const woyao:Partial<PersonProps> = {};
  • Required: 将类型定义的所有属性都修改为必填
    1
    2
    3
    type Required<T> = { [P in keyof T]-?: T[P] };
    interface PersonProps = { name?: string; age: number; };
    const woyao:Required<PersonProps> = {name: 'woyao', age: 23};
  • Pick: 将类型定义的部分属性作为一个新类型
    1
    2
    3
    4
    5
    6
    // k extends keyof T === 'props1' | 'props2' | ....
    type Pick<T, K extends keyof T> = {
    [P in K]: T[P];
    }
    interface PersonProps = { name: string; age: number; };
    const woyao: Pick<PersonProps, "name"> = {name: 'woyao' };
  • Record: 以 typeof 格式快速创建一个类型,此类型包含一组指定的属性且都是必填。
    1
    2
    3
    4
    5
    // K 是一个union类型,比如: type PersonProps = 'name' | 'age' | 'sex'
    type Record<K extends string, T> = {
    [P in K]: T;
    }
    type PersonProps = Record<'name' | 'sex', string>
  • Exclude: 排除
    1
    2
    3
    type Exclude<T, U> = T extends U ? never : T;
    // type A = 'a'
    type A = Exclude<'x' | 'a', 'x' | 'y' | 'z'>
  • Omit: 省略
    1
    2
    3
    4
    5
    6
    7
    8
    type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
    interface User {
    id: number;
    age: number;
    name: string;
    };
    // 相当于: type OmitUser = { age: number; name: string; }
    type OmitUser = Omit<User, "id">
文章作者: woyao
文章链接: https://chenwoyao.github.io/2021/04/23/前端笔记/javascript系列/typescript语法大全/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 woyao的博客