TypeScript:通过删除特定字符串来限制对象键

9jyewag0  于 2023-08-08  发布在  TypeScript
关注(0)|答案(1)|浏览(138)

我想定义一个记录类型,它允许键是所有字符串,除了一些特定的值。如何做到这一点?我有以下类型:

// Actual type of KvValue is irrelevant here, but here is a subset of it
type KvValue = string | number | boolean

type Mutation<T extends KvValue> = (value: T) => KvValue

type MutationRecord<T extends KvValue> = Record<
  Exclude<string, "id" | "versionstamp" | "value">,
  Mutation<T>
>

const record: MutationRecord<number> = {
  id: (n) => n * 2,
}

字符串
MutationRecord永远不应该允许“id”、“versionstamp”和“value”的键。我还需要在联合类型中推断出这一点,以便某些类型T & MutationRecord知道来自T的值,如果其键在MutationRecord中不允许,则不会接收Mutation类型,而只能接收T中的类型。

laximzn5

laximzn51#

您可以使用带有可选never的交集作为禁用密钥:

type KvValue = string | number | boolean;

type Mutation<T extends KvValue> = (value: T) => KvValue;

type MutRecord<T extends KvValue> = Record<string, Mutation<T>> &
  {id?: never, versionstamp?: never, value?: never}

const record: MutRecord<number> = {
  id: (n) => n * 2, // error
};

字符串
Playground

相关问题