typescript 如何在这样设计的类型中添加新属性

yqkkidmi  于 2023-10-22  发布在  TypeScript
关注(0)|答案(3)|浏览(122)

我想给类型添加一个新属性
现在我的类型ValidateResult

type FieldKey = 'internal' | 'external'

export type ValidateResult = {
  [x in FieldKey]: any
}

但是现在,我想给它添加一个新的Key。但我不能添加这个新的关键字类型字段,所以,我做了一些像下面。但它抛出sytax错误。

export type ValidateResult = {
  [x in FieldKey]: any
  newKey: any
}
lvmkulzt

lvmkulzt1#

通常我喜欢在扩展对象类型时使用交叉类型。

type FieldKey = 'internal' | 'external'

type ValidateResult = {
  [x in FieldKey]: any;
} & {
  newKey: any;
}
// type ValidateResult = {
//     internal: any;
//     external: any;
//     newKey: any;
// }

TypeScriptPlayground
但是,如果对象中的所有属性都具有相同的值类型,则可以在Mapped Type中使用新的Union Type,如下所示:

type FieldKey = 'internal' | 'external'

type ValidateResult = {
  [x in FieldKey | "newKey"]: any;
}
// type ValidateResult = {
//     internal: any;
//     external: any;
//     newKey: any;
// }

TypeScriptPlayground

dgenwo3n

dgenwo3n2#

为什么不添加一个新的类型定义,并带有缺少的键,就像这样:

type FieldKey = 'internal' | 'external'
type ValidateResultKey = FieldKey | 'you_done_goofed'

export type ValidateResult = {
  [x in ValidateResultKey]: any
}

或者,如果需要另一种类型,可以使用&运算符并将其与另一种类型合并组合

type FieldKey = 'internal' | 'external'

export type ValidateResult = {
  [x in FieldKey]: any;
} & {
  test: string;
}

const test = {
  internal: "",
  external: "",
  test: "",
} as ValidateResult;
ni65a41a

ni65a41a3#

如果你想更通用,你可以扩展基类型:

type FieldKey = 'internal' | 'external'

type ValidateResult<T extends (string | undefined) = undefined> = {
  [x in (FieldKey | T) as x extends undefined ? never : x]: any;
}

// Now you can define your custom types:

type ValidateResultWithNewField= ValidateResult<'newField'>;

// or event

type ValidateResultWithMultiNewFields = ValidateResult<'field1' | 'f2' | 'anotherField' | 'etcField'>;

相关问题