接口定义练习
interface Student {
name: string,
age: number,
hobbies?: string[],
}
函数定义练习
type MyMethod<T extends string | number> = (arg: T) => T extends string ? number : string
interface MyMethod<T extends string | number> {
(arg: T): T extends string ? number : string
}
const mm1: MyMethod<string> = (arg: string) => {
return 0
}
const mm2: MyMethod<number> = (arg: number) => {
return ''
}
泛型工具定义练习1
type MyRequired<T> = {
[P in keyof T]-?: T[P]
}
type RequiredStudent = Required<Student>
type MyRequiredStudent = MyRequired<Student>
type MyPartial<T> = {
[P in keyof T]+?: T[P]
}
type PartialStudent = Partial<Student>
type MyPartialStudent = MyPartial<Student>
type MyReadonly<T> = {
readonly [P in keyof T]: T[P]
}
type RoStudent = Readonly<Student>
type MroStudent = MyReadonly<Student>
type MyNonNullable<T> = T & {}
type NnResult = NonNullable<Student | null | number>
type MnnResult = MyNonNullable<Student | null | number>
type MyReturnType<F extends (...args: any) => any> = F extends (...args: any) => infer R ? R : void
type Result = ReturnType<MyMethod<string>>
type MyResult = MyReturnType<MyMethod<string>>
泛型工具定义练习2
type MyExtract<K0, K1> = K0 extends K1 ? K0 : never
type Extracted = Extract<keyof Student, 'name' | 'gender'>
type MyExtracted = MyExtract<keyof Student, 'name' | 'gender'>
type MyExclude<T, U> = T extends U ? never : T
type Excluded = Exclude<keyof Student, 'name' | 'gender'>
type MyExcluded = MyExclude<keyof Student, 'name' | 'gender'>
type MyPick<T, K extends keyof T> = {
[P in K]: T[P]
}
type Picked = Pick<Student, 'name' | 'age'>
type MyPicked = MyPick<Student, 'name' | 'age'>
type MyOmit<T, K extends keyof T> = {
[P in keyof T as P extends K ? never : P]: T[P]
}
type Omitted = Omit<Student, 'name' | 'age'>
type MyOmitted = MyOmit<Student, 'name' | 'age'>
type MyRecord<K extends keyof any, T> = {
[P in K]: T
}
type Recorded = Record<string, any>
type MyRecorded = MyRecord<string, any>