如何创建一个具有未知数量的字符串属性和一个特定 属性 数字类型的接口?

How to create an interface with an unknown amount of string properties and one specific property with number type?

我有一个对象,其中包含未知数量的错误消息,并且只有一个 属性 带有类型编号。如何为此对象创建接口?

  interface IFormErrors {
    [key: string]: string; // So here is an unknown amount of strings
  }

  const initialFormErrors: IFormErrors = {
    nameErr: "",
    emailErr: "",
    linkErr: "",
    errorCounter: 0,
  };

准确实现您正在寻找的方法是使用交集类型:

  type IFormErrors = { errorCounter: number } & {
    [key: string]: string; // So here is an unknown amount of strings
  }

  const initialFormErrors: IFormErrors = {
    nameErr: "",
    emailErr: "",
    linkErr: "",
    errorCounter: 0,
  };

这是一种解决方法,因为 Typescript 不允许您在定义索引签名后拥有其他类型的属性。推荐的方法是使用嵌套索引签名来避免这个问题:

interface IFormErrors {
  errorCounter: number;
  // you can name this property whatever you like, `errors` was just
  // what I came up with
  errors: { 
    [key: string]: string; // So here is an unknown amount of strings
  }
}

我建议阅读 Typescript Deep Dive gitbook 的这一部分,以了解有关如何有效使用索引签名的更多信息:https://basarat.gitbook.io/typescript/type-system/index-signatures#declaring-an-index-signature

这是可行的,但有一些限制:

interface IFormErrors {
    [key: string]: string; // So here is an unknown amount of strings
}

type Result = IFormErrors & {
    errorCounter: number;
}

const merge = <T, U>(a: T, b: U) => ({ ...a, ...b })
const build = (obj: IFormErrors, errorCounter: number) => merge(obj, { errorCounter })

const result = build({ a: '2' }, 5)

const anyProperty = result.sdf // string
const numberProperty = result.errorCounter // number



/**
 * But you are unable to create literal type
 */
const y: Result = { // error
    a: '23',
    errorCounter: 42
}

result 变量具有 Result 类型 - 这正是您想要的