使用“排除”运算符不起作用。
type test = Exclude<'a'|'b'|string, string>
// produces type test = never
Run Code Online (Sandbox Code Playgroud)
我可以理解为什么“除了字符串”也意味着排除所有字符串文字,但是我如何才能获得'a'|'b'out 'a'|'b'|string呢?
如果需要,假定使用最新的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
}
Run Code Online (Sandbox Code Playgroud)
现在,我想做的是获得KNOWN属性的并集:
type KnownProperties = Exclude<keyof JSONSchema4, string|number>
Run Code Online (Sandbox Code Playgroud)
可以理解的是,这失败了并且给出了一个空类型。
如果您正在阅读本文,但是我被公交车撞到了,可以在GitHub线程中找到答案。