无法从过滤类型中删除永不带有属性以获取剩余键

时间:2019-05-07 01:45:35

标签: typescript typescript-generics

我正在尝试从对象A(typeof MovementState)中提取我类型B("Standing" | "Lying")的字符串文字列表中不存在的键到字符串文字并集({{ 1}})。

我有以下代码:

"Walking"|"Running"|"Crawling"|"Climbing"

在这一点上,我希望enum MovementState { Standing, Walking, Running, Lying, Crawling, Climbing } type StillStates = "Standing" | "Lying"; type ExcludeProperties<U, V> = { -readonly [P in keyof U]: P extends (V | number) ? never : string }[keyof U]; type MovingStates = ExcludeProperties<typeof MovementState, StillStates>; 的类型为MovingStates,但其类型为"Walking"|"Running"|"Crawling"|"Climbing"。我在做什么错了?

使用Typescript 3.2编译。

2 个答案:

答案 0 :(得分:2)

您可以在映射中使用Exclude摆脱不想要的属性,而使用keyof来获取密钥:

type ExcludeProperties<U, V> = keyof { -readonly [P in Exclude<keyof U, V>]: U[P] };

实际上,由于该类型的内部结构始终被丢弃,因此可以将其简化为以下内容:

type ExcludeProperties<U, V> = Exclude<keyof U, V>;

此外,要添加更多类型安全性,您可以向V添加约束:

type ExcludeProperties<U, V extends keyof U> = Exclude<keyof U, V>;

答案 1 :(得分:1)

答案包含在原始TypeScript文档中(在Distributive conditional types的示例中)

type ExcludeProperties<T, U> = T extends U ? never : T;

type MovingStates = ExcludeProperties<keyof typeof MovementState, StillStates>;

// MovingStates will be of type "Walking" | "Running" | "Crawling" | "Climbing"