1、基础类型
TS中的数据类型有很多,如下:
-
Number类型
let a: number = 5
-
String类型
let str: string = 'hello ts'
-
Boolean类型
let isDone: boolean = true
-
Null和Undefined类型
let n1: null = null
let u1: undefined = undefined
// -------------------------------
let n2: null = undefined
let u2: undefined = null
-
Void类型
function fn():void{
console.log('This is a fn,but return is void')
}
void用于表示返回空
-
Any类型
let any1: any = 'xxx'
Any类型的变量可以赋值任意类型的值
2、复杂类型
- Array
let arr: number[] = [1, 2, 3];
let arr: Array<number> = [1, 2, 3];
- tuple 元组
let tuple:[number,string]= [1, "层级"]
- function 函数
function add(arg1: string, arg2: string): string
function add(arg1: number, arg2: number): number
// 或者
function add(arg1: string | number, arg2: string | number):any {
if (typeof arg1 === 'string' && typeof arg2 === 'string') {
return arg1 + arg2
} else if (typeof arg1 === 'number' && typeof arg2 === 'number') {
return arg1 + arg2
}
}
console.log(add('fly', 'zs'))
console.log(add(1, 2))
- union 联合类型
let a: number | string;
a = 10;
a = 'hajah';
- object 对象
let obj7: {name: string, age: number};
obj7 = {name: 'yan', age: 18};
3、断言 type interence
function add(x: number, y?: number): number {
return x + <number>y;
}
function add(x: number, y?: number): number {
return x + (y as number);
}
4、类型守卫 type guard
遇到联合类型,根据typeof、instanceof判断
function phone(param: Product | Goods) {
console.log("函数中类型:", typeof param);
}
5、类 class
class Person {
// 成员变量
public name: string
protected age: number
private sex: string
// 构造函数
constructor(name: string, age: number, sex: string) {
this.name = name
this.age = age
this.sex = sex
}
say(): void {
console.log(this.name)
}
}
class ZS extends Person {
constructor(name: string, age: number, sex: string) {
super(name, age, sex)
}
say(): void {
console.log(this.age + '111')
}
}
const zs = new ZS('zs', 18, '男')
6、接口 interface
interface Device {
type:string,
with:number,
[key:string]:string
}
interface encrypt {
(key: string, val: string): string
}
7、枚举 enum
enum Direction {
NORTH,
SOUTH,
EAST,
WEST,
}
let dir: Direction = Direction.NORTH;
8、泛型
function getData<T>(value: T): T {
return value
}
interface Search {
<T,Y>(name:T,age:Y):T
}
let fn:Search = function <T, Y>(name: T, id:Y):T {
console.log(name, id)
return name;
}
interface Person {
name:string;
age:number;
}
function student<T extends Person>(arg: Partial<T>):Partial<T> {
return arg;
}
interface PageInfo {
title: string
}
type Page = 'home'|'about'|'other';
const x: Record<Page, PageInfo> = {
home: { title: "xxx" },
about: { title: "aaa" },
other: { title: "ccc" },
};
interface Todo {
title:string,
desc:string,
time:string
}
type TodoPreview = Pick<Todo, 'title'|'time'>;
const todo: TodoPreview ={
title:'吃饭',
time:'明天'
}
export type NullableKeys<T, K extends keyof T> = Omit<T, K> & { [P in K]?: T[P] };
type NullableUser = NullableKeys<User, 'age' | 'email'>;
type T0 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"
const t:T0 ='b';
// 获取函数返回类型
type T0 = ReturnType<() => string>; // string
type T1 = ReturnType<(s: string) => void>; // void
type T2 = ReturnType<<T>() => T>; // {}
type T3 = ReturnType<<T extends U, U extends number[]>() => T>; // number[]
type T4 = ReturnType<any>; // any
type T5 = ReturnType<never>; // any
type T6 = ReturnType<string>; // Error
type T7 = ReturnType<Function>; // Error
//
type FieldType = {name?: string}
const onFinish: FormProps<FieldType>[‘onFinish’] = values =>{ }
interface FormProps<values = any> extends Omit<RcFormProps<values>, ‘form’>{
form?: FormIntance<values>;
name?: string;
...
onFinish?: Callbacks<values> [‘onFinish’] ;
}
interface Callbacks <values = any> {
onFinish?: (values: values) => void;
onValuesChange?: (changeValues:any,values: values) => void;
}
9、类型别名
type Name = string;
type NameResolver = () => string;
type NameOrResolver = Name | NameResolver;
function getName(n: NameOrResolver): Name {
if (typeof n === 'string') {
return n;
} else {
return n();
}
}
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'
// index.ts(7,47): error TS2345: Argument of type '"dblclick"' is not assignable to parameter of type 'EventNames'.
10、交叉类型
let obj5: {name:string} & {age:number}
obj5 = {name: '悟空', age: 10}