1、泛型
function esayIdentity<T> (arg: T): T{
return arg
}
let output1 = esayIdentity<string>("myString")
let output2 = esayIdentity("myString")
console.log("output1", output1)
console.log("output2", output2)
2、泛型类
interface GenericInterface<U> {
value: U
getIdentity: () => U
}
class IdentityClass<T> implements GenericInterface<T>{
value: T
constructor (value: T){
this.value = value
}
getIdentity (): T{
return this.value
}
}
const myNumberClass = new IdentityClass<Number>(68)
console.log(myNumberClass.getIdentity())
const myStringClass = new IdentityClass<string>("Semlinker!")
console.log(myStringClass.getIdentity())
3、泛型类型
interface GenericIdentityFn<T> {
(arg: T): T;
}
function identity<T> (arg: T): T{
return arg
}
let myIdentity: GenericIdentityFn<number> = identity
console.log("泛型类型", myIdentity(123))
4、泛型约束:extends、keyof
interface Lengthwise {
length: number;
}
function constraintIdentity<T extends Lengthwise> (arg: T): T{
console.log("参数长度:", arg.length)
return arg
}
constraintIdentity("constraintIdentity")
interface Person {
name: string;
age: number;
location: string;
}
type K1 = keyof Person;
type K2 = keyof Person[];
type K3 = keyof { [x: string]: Person };
class Stack<T>{
private data: T[] = []
push (item:T){
return this.data.push(item)
}
pop ():T | undefined{
return this.data.pop()
}
}
const s1 = new Stack<number>()
s1.push(18)
import axios from "axios"
interface API {
"/book/detail": {
id: number,
},
"/book/comment": {
id: number
comment: string
}
}
function request<T extends keyof API> (url: T, obj: API[T]){
return axios.post(url, obj)
}
export default {}