【发布时间】:2019-01-27 23:44:14
【问题描述】:
使用排除运算符不起作用。
type test = Exclude<'a'|'b'|string, string>
// produces type test = never
我可以理解为什么“字符串除外”也意味着排除所有字符串文字,但是如何从'a'|'b'|string 中获得'a'|'b'?
如果需要,请使用最新的 TypeScript。
用例如下:
假设第三方库定义了这种类型:
export interface JSONSchema4 {
id?: string
$ref?: string
$schema?: string
title?: string
description?: string
default?: JSONSchema4Type
multipleOf?: number
maximum?: number
exclusiveMaximum?: boolean
minimum?: number
exclusiveMinimum?: boolean
maxLength?: number
minLength?: number
pattern?: string
// to allow third party extensions
[k: string]: any
}
现在,我想做的是获得已知属性的联合:
type KnownProperties = Exclude<keyof JSONSchema4, string|number>
可以理解的是,这会失败并给出一个空类型。
如果你正在阅读这篇文章,但我被公共汽车撞了,这个问题的答案可能在 this GitHub thread 中找到。
【问题讨论】:
-
'a'|'b'|string简化为string,然后您才能对其进行任何操作。您必须更改生成此类型的任何代码。那个代码是什么? -
@MattMcCutchen 联合是接口上
keyof的结果。我现在正在编辑问题。 -
问题的症结在于删除索引签名。在搞砸了几分钟后,我无法找到解决办法。在this question,jcalz 声称无法做到,我倾向于相信他。
-
@MattMcCutchen 我找到了一种方法,我将其添加为答案。
-
太棒了......有人去另一个线程并回答它或在此处链接它。