函数

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')

泛型类

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();

泛型接口

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
})()