使用“排除”运算符不起作用。
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线程中找到答案。
我一直在尝试创建一个由T值为字符串的类型键组成的类型.在伪代码中它会是keyof T where T[P] is a string.
我能想到的唯一方法是分两步:
// a mapped type that filters out properties that aren't strings via a conditional type
type StringValueKeys<T> = { [P in keyof T]: T[P] extends string ? T[P] : never };
// all keys of the above type
type Key<T> = keyof StringValueKeys<T>;
Run Code Online (Sandbox Code Playgroud)
然而,TS编译器说这Key<T>简直等于keyof T,即使我通过将它们设置为never使用条件类型来过滤掉其值不是字符串的键.
所以它仍然允许这样,例如:
interface Thing {
id: string;
price: number;
other: { stuff: boolean };
}
const key: Key<Thing> …Run Code Online (Sandbox Code Playgroud)