我有以下通用映射类型:
export type KeyRules<Input> = {
[K in keyof Input]?: Rule<Input[K], Input>};
我想定义另一个看起来像这样的:
export type ExtendedRules<Input> = Omit<
Record<string, Rule<Input, Input>>,
keyof Input
>;
或
export type ExtendedRules<Input> = {
[K in Exclude<string, keyof Input>]?: Rule<Input, Input>
};
或
export type ExtendedRules<Input> = Record<
Exclude<string, keyof Input>,
Rule<Input, Input>
>;
然后我将定义第三种类型:
export type Rules = KeyRules & ExtendedRules;
但是我似乎无法排除输入的键。 ExtendedRules<Input>
始终等于 Record<string, Rule<Input, Input>
.
我还尝试了条件类型:
export type Rules<Input> = {
[k: string]: k extends keyof Input ? Rule<Input[typeof k], Input> : Rule<Input, Input>
}
这也不起作用
实际上是否可能有一种否定的映射对象类型?
最佳答案
这可能适用于您的用例,也可能不适用于您的用例,但您可以将要省略的键的值类型声明为never
,而不是尝试完全删除键。这通常会产生相同的效果。
示例:
type bannedKeys = "a" | "b" | "c"
type myType = {
[key: string]: string;
} & {
[key in bannedKeys]: never;
}
declare const obj: myType;
const test1 = obj["a"]; // test1 has type 'never'
const test2 = obj["d"]; // test2 has type 'string'
关于typescript - 从记录中排除键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72589497/