函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function getVal<T>(obj: T, k: keyof T) {
return obj[k]
}

let obj1 = {
x: 1,
y: 2
}

let obj2 = {
username: 'xiaokang',
age: 18
}

getVal<typeof obj1>(obj1, 'x')
getVal<typeof obj2>(obj2, 'username')

泛型类

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
abstract class Component<T1, T2> {
props: T1;
state: T2;
constructor(props: T1) {
this.props = props;
}
abstract render(): string;
}
interface IMyComponentProps {
val: number;
}
interface IMyComponentState {
x: number;
}
class MyComponent extends Component<IMyComponentProps, IMyComponentState> {
constructor(props: IMyComponentProps) {
super(props);
this.state = {
x: 1
}
}
render() {
this.props.val;
this.state.x;
return '<myComponent />';
}
}
let myComponent = new MyComponent({val: 1});
myComponent.render();

泛型接口

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
interface IResponseData<T> {
code: number
message?: string
data: T
}
// 用户接口
interface IResponseUserData {
id: number
username: string
email: string
}
// 文章接口
interface IResponseArticleData {
id: number
title: string
author: IResponseUserData
}
async function getData<U>(url: string) {
let resPonse = await fetch(url)
let data: Promise<IResponseData<U>> = await resPonse.json()
return data
}

;(async function () {
let userData = await getData<IResponseUserData>('/user')
userData.data.email
})()