我有如下类型:
type Entity =
| {
type: 'user' | 'person';
id: string;
}
| {
type: 'animal';
id: number;
};
Run Code Online (Sandbox Code Playgroud)
现在我想从中提取类型:
type Animal = Extract<Entity, {type: 'animal'}>- 完美运行(返回{ type: 'animal'; id: number; });
type User = Extract<Entity, {type: 'user'}>- 返回never。
我怎样才能让它返回{ type: 'user'; id: string; }
?
提供的文档Extract<T, U>说:
从 T 中提取可分配给 U 的类型
并且{ type: 'user' | 'person', id: string }不可分配给{ type: 'user' }
declare const entity: Entity
const user: { type: 'user' } = entity
/*
Type 'Entity' is not assignable to type '{ type: "user"; }'.
Type '{ type: "user" | "person"; id: string; }' is not assignable to type '{ type: "user"; }'.
Types of property 'type' are incompatible.
Type '"user" | "person"' is not assignable to type '"user"'.
Type '"person"' is not assignable to type '"user"'.(2322)
*/
Run Code Online (Sandbox Code Playgroud)
这意味着您不能用来Extract执行此操作。
但是您可以做的是使用交集 ( &),它将修剪掉该判别式无法匹配的任何联合成员。
type User = Entity & { type: 'user' }
const user: User = { type: 'user', id: 'abc' }
user.id // type: string
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
259 次 |
| 最近记录: |