Open yunliuyan opened 1 year ago
和pick取反就醒了
type MyOmit<T, K> = {
[key in keyof T as key extends K ? never : key]: T[key]
}
type EasyOmit<T, U extends keyof T> = {
[k in keyof T]: k extends U ? never : T[k];
};
interface OmitType {
name: string;
description: string;
address: string;
}
const easyOmitTest: EasyOmit<OmitType, 'name' | 'description'> = {
name: "字节猿", // Error: The expected type comes from property 'name' which is declared here on type 'EasyOmit<OmitType, "name" | "description">'
description: "字节猿喜欢readonly", // Error: The expected type comes from property 'description' which is declared here on type 'EasyOmit<OmitType, "name" | "description">'
address: "我家在陕西", // Ok
};
type error = EasyOmit<OmitType, 'name' | 'test'> // Error: Type '"test"' is not assignable to type 'keyof OmitType'
`type MyOmit<T, P extends keyof T> = {
}`
type MyOmit<T, K extends keyof T> = {
[P in keyof T]: P extends K ? never : T[P];
};
// 不使用 Omit 实现 TypeScript 的 Omit<T, K> 泛型。
// Omit 会创建一个省略 K 中字段的 T 对象。
type MyOmit<T, K extends keyof T> = {
[key in keyof T as key extends K ? never : key]: T[key]
}
interface Todo4 {
title: string
description: string
completed: boolean
// test: never
}
type TodoPreview4 = MyOmit<Todo4, 'description' | 'title'>
const todo: TodoPreview4 = {
completed: false,
// test: false as never
}
实现 Omit
不使用
Omit
实现 TypeScript 的Omit<T, K>
泛型。Omit
会创建一个省略K
中字段的T
对象。例如:
测试案例:
相关挑战