TypeScript 条件排除类型从接口中排除 [英] TypeScript conditional Exclude type exclude from interface

查看:54
本文介绍了TypeScript 条件排除类型从接口中排除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据文档,我可以使用预定义的排除类型从特定类型中排除某些属性:

According to documentation, I can use predefined Exclude type to exclude certain properties from certain type:

type Test = string | number | (() => void);

type T02 = Exclude<Test, Function>;

但是,如果我有 Test 接口而不是 Test 类型,它似乎不起作用.如何在以下情况下获得类似的结果?

However if instead of Test type I'd have Test interface, it doesn't seems to work. How can I achieve similiar result in below case?

interface Test {
  a: string;
  b: number;
  c: () => void;
} 

// get somehow interface with excluded function properties??

推荐答案

要获得这种效果,您需要弄清楚哪些属性与 Function 匹配,然后有选择地排除它们.等效地,我们找到哪些属性与 Function 不匹配,然后有选择地包含它们.这不仅仅是排除联合的某些部分更复杂;它涉及映射类型以及条件类型.

To get this effect you need to figure out which properties match Function, and then selectively exclude them. Equivalently we find which properties do not match Function, and then selectively include them. This is more involved than just excluding some pieces of a union; it involves mapped types as well as conditional types.

一种方法如下:

type ExcludeMatchingProperties<T, V> = Pick<
  T,
  { [K in keyof T]-?: T[K] extends V ? never : K }[keyof T]
>;

type T02 = ExcludeMatchingProperties<Test, Function>;
// type T02 = {
// a: string;
// b: number;
// }

<小时>

检查 ExcludeMatchingProperties,我们可以注意到类型 { [K in keyof T]-?: T[K] 扩展了 V ?never : K }[keyof T] 将返回 T 中其属性不可分配给 V 的键.


Examining ExcludeMatchingProperties<T, V>, we can note that the type { [K in keyof T]-?: T[K] extends V ? never : K }[keyof T] will return the keys in T whose properties are not assignable to V.

如果 TTest 并且 VFunction,这就变成了

If T is Test and V is Function, this becomes something like

{ 
  a: string extends Function ? never : "a"; 
  b: number extends Function ? never : "b"; 
  c: ()=>void extends Function ? never : "c" 
}["a"|"b"|"c"]

,变成

{ a: "a"; b: "b"; c: never }["a"|"b"|"c"]

,变成

{ a: "a"; b: "b"; c: never }["a"] | 
{ a: "a"; b: "b"; c: never }["b"] | 
{ a: "a"; b: "b"; c: never }["c"]

"a" | "b" | never

"a" | "b"

一旦我们有了这些键,我们就从 TPick 它们的属性(使用 Pick 实用程序类型):

Once we have those keys, we Pick their properties them from T (using the Pick<T, K> utility type):

Pick<Test, "a" | "b">

成为想要的类型

{
  a: string,
  b: number
}

好的,希望有帮助;祝你好运!

Okay, hope that helps; good luck!

链接到代码

这篇关于TypeScript 条件排除类型从接口中排除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆