Typescript 类型体操 —— 实现 Extract
要求
从某个联合类型中,筛选出和另外一个联合类型相交的部分。
// your code
// type YourTypeFunc...
type Union1 = "A" | "B" | "C";
type Union2 = "A" | "B";
// result
type res = YourTypeFunc<Union1, Union2> // "A" | "B"
可参考的知识点
- A conditional type T extends U ? X : Y is either resolved to X or Y, or deferred because the condition depends on one or more type variables.
- Conditional types in which the checked type is a naked type parameter are called distributive conditional types. Distributive conditional types are automatically distributed over union types during instantiation. For example, an instantiation of T extends U ? X : Y with the type argument A | B | C for T is resolved as (A extends U ? X : Y) | (B extends U ? X : Y) | (C extends U ? X : Y).
知识链接
问题 & 解答
使用场景
// 判断两个对象的部分公有fields属性值是否相等
// @ts-ignore JS写法
function isEqual1(obj1, obj2, fields) {
// @ts-ignore
return fields.every((field) => obj1[field] ===obj2[field]);
}
// 用到Extract的TS写法
function isEqual2<T extends Record<string, any>, K extends Record<string, any>> (obj1: T, obj2: K,fields: Array<Extract<keyof T, keyof K>>
): boolean {
return fields.every((field) => obj1[field] ===obj2[field]);
}
isEqual1(
{ a: 1, b: 1, c: 1},
{ a: 1, b: 2 },
['c']
)
isEqual2(
{ a: 1, b: 1, c: 1},
{ a: 1, b: 2 },
['c'] // Type '"c"' is not assignable to type '"a" | "b"'.
)
转载自:https://juejin.cn/post/6981286316998656008