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



我有一个对象,它包含未知数量的错误消息和一个类型号为的属性。如何为此对象创建接口?

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-索引签名

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

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类型——这正是您想要的

最新更新