[英]TypeScript conditional Exclude type exclude from interface
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>;
However if instead of Test type I'd have Test interface, it doesn't seems to work. 但是,如果我不是Test类型,而是具有Test接口,则它似乎无法正常工作。 How can I achieve similiar result in below case?
在以下情况下如何获得相似的结果?
interface Test {
a: string;
b: number;
c: () => void;
}
// get somehow interface with excluded function properties??
To get this effect you need to figure out which properties match Function
, and then selectively exclude them. 为了获得这种效果,您需要确定哪些属性与
Function
匹配,然后有选择地排除它们。 Equivalently we find which properties do not match Function
, and then selectively include them. 等效地,我们找到哪些属性与
Function
不匹配,然后有选择地包括它们。 This is more involved than just excluding some pieces of a union; 这不仅涉及排除工会的某些部分,还涉及更多的工作。 it involves mapped types as well as conditional types .
它涉及映射类型以及条件类型 。
One way to do this is as follows: 一种方法如下:
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;
// }
Examining ExcludeMatchingProperties<T, V>
, we can note that the type { [K in keyof T]-?: T[K] extends V ? never : K }[keyof T]
检查
ExcludeMatchingProperties<T, V>
,我们可以注意到类型{ [K in keyof T]-?: T[K] extends V ? never : K }[keyof T]
{ [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
. { [K in keyof T]-?: T[K] extends V ? never : K }[keyof T]
将返回T
的属性不可分配给V
。
If T
is Test
and V
is Function
, this becomes something like 如果
T
为Test
且V
为Function
,则这类似于
{
a: string extends Function ? never : "a";
b: number extends Function ? never : "b";
c: ()=>void extends Function ? never : "c"
}["a"|"b"|"c"]
, which becomes ,即成为
{ a: "a"; b: "b"; c: never }["a"|"b"|"c"]
, which becomes ,即成为
{ a: "a"; b: "b"; c: never }["a"] |
{ a: "a"; b: "b"; c: never }["b"] |
{ a: "a"; b: "b"; c: never }["c"]
, or , 要么
"a" | "b" | never
, or , 要么
"a" | "b"
Once we have those keys, we Pick
their properties them from T
(using the Pick<T, K>
utility type ): 有了这些键之后,我们从
T
Pick
它们的属性(使用Pick<T, K>
实用程序类型 ):
Pick<Test, "a" | "b">
which becomes the desired type 成为所需的类型
{
a: string,
b: number
}
Okay, hope that helps; 好的,希望能有所帮助; good luck!
祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.