开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第2天,点击查看活动详情
一、类型的参数化
function bar<Type>(arg: Type): Type {
return arg
}
const res1 = bar<number>(123)
const res2 = bar<string>("abc")
const res3 = bar<{name: string}>({ name: "myName"})
省略的写法(更具体)
const res4 = bar("cba")
const res5 = bar(321)
let定义不如const具体
二、手写useState
function useState<Type>(initialState: Type): [Type, (newState: Type) => void] {
let state = initialState
function setState(newState: Type) {
state = newState
}
return [state, setState]
}
const [count, setCount] = useState(123)
const [message, setMessage] = useState("abc")
三、传入多个类型
function foo<Type, Element>(arg1: Type, arg2: Element) {
}
四、缩写(常见)
T: Type
K、V: key、value
E: Element
O: Object
五、泛型接口
interface IKun<Type = string> {// string默认值
name: Type
age: number
slogan: Type
}
const ikun1: IKun<string> = {
name: "myName",
age: 21,
slogan: "你干嘛,哎呦"
}
六、泛型类
class Point<Type = number> {
x: Type
y: Type
constructor(x: type, y: Type) {
this.x = x
this.y = y
}
}
const p1 = new Point(10, 20)// number
const p2 = new Point("123", "abc")// string
七、泛型约束
interface ILength {
length: number
}
// 获取传入内容,必须有length属性:
function getLength<T extends ILength>(args: T): T {
return args.length
}
八、泛型参数使用约束
interface IKun {
name: string
age: number
}
// typeof用处:
type IKunKeys = keyof IKun // "name" | "age"
function getObjectProperty<O, K extends keyof O>(obj: O, key: K) {
return obj[key]
}
const info = {
name: "myName",
age: 21,
}
const name = getObjectProperty(info, "name")// myName