我想要使用TypeScript和数组来实现在一个对象数组前添加新对象的操作,具体是利用扩展运算符。
以下为相关设置:
定义类型的接口:
interface KeyValuePair {
key: string;
value: string;
}
一个对象类型的数组:
const kvpset: KeyValuePair[] = [
{ key: "1", value: "One" },
{ key: "2", value: "Two" },
{ key: "3", value: "Three" },
{ key: "4", value: "Four" },
{ key: "5", value: "Five" },
{ key: "6", value: "Six" },
{ key: "7", value: "Seven" },
{ key: "8", value: "Eight" },
{ key: "9", value: "Nine" },
];
我的前置类型化对象工具:
const kvpzero: KeyValuePair = { key: "0", value: "Zero" };
第一次尝试:
const kvpAll: KeyValuePair[] = { kvpzero, ...kvpset };
编辑器出错:
属性) kvpzero: KeyValuePair 类型 '{ length: number; toString(): string; toLocaleString(): string; pop(): KeyValuePair; push(...items: KeyValuePair[]): number; concat(...items: ConcatArray[]): KeyValuePair[]; concat(...items: (KeyValuePair | ConcatArray<...>)[]): KeyValuePair[]; ... 26 more ...; kvpzero: KeyValuePair; }' 无法分配给类型 'KeyValuePair[]'。 对象文字只能指定已知属性,而 'kvpzero' 在类型 'KeyValuePair[]' 中不存在。ts(2322)
好的,我有点不知所措。我试试这个:
const kvpzeroAsArray: KeyValuePair[] = [{ key: "0", value: "Zero" }];
这并不会引发“编译器错误”:
const kvpAll: KeyValuePair[] = { ...kvpzeroAsArray, ...kvpset };
使用 tsc 和 node 运行它(编辑器是 Visual Studio Code)。在控制台中使用 console.log() 输出 kvpAll 对象的结果:
kvpAll is {
'0': { key: '1', value: 'One' },
'1': { key: '2', value: 'Two' },
'2': { key: '3', value: 'Three' },
'3': { key: '4', value: 'Four' },
'4': { key: '5', value: 'Five' },
'5': { key: '6', value: 'Six' },
'6': { key: '7', value: 'Seven' },
'7': { key: '8', value: 'Eight' },
'8': { key: '9', value: 'Nine' }
}
我看到了以下三点。1. 对象现在是一个对象,而不是数组。2. 我的零丢失了。我不知道为什么这不起作用,也不知道为什么无法获得预期的结果。3. 它甚至不是我想要的相同类型的输出。它将属性作为数字,并将值作为对象:'0': { key: '1', value: 'One' }
,而不仅仅是 { key: '1', value: 'One' }
。
在网上搜索,似乎Object.assign()
机制是一个可行的方法。
const assignedkvp = (<any>Object).assign(kvpzeroAsArray, kvpset);
输出结果(再次使用console.log()
):
assignedkvp is [
{ key: '1', value: 'One' },
{ key: '2', value: 'Two' },
{ key: '3', value: 'Three' },
{ key: '4', value: 'Four' },
{ key: '5', value: 'Five' },
{ key: '6', value: 'Six' },
{ key: '7', value: 'Seven' },
{ key: '8', value: 'Eight' },
{ key: '9', value: 'Nine' }
]
嗯...和 spread 操作符类似的结果。对象并未随着 spread 的变化而改变,但我仍然没有看到我想要的假装结果。
我已经不知所措了。我不明白如何使用 spread 操作符或 assign 函数来获得想要的结果。如果有任何见解,我将不胜感激。这是我的当前解决方案。暴力方法:
const prePendObjectToArray = <T>(object: T, array: T[]): T[] => {
let returnArray = [] as T[];
if (array && array.length > 0 && object) {
for (let i = 0; i < array.length + 1; i++) {
if (i === 0) {
returnArray.push(object);
} else {
returnArray.push(array[i - 1]);
}
}
}
return returnArray;
};
用法:
const newArray = prePendObjectToArray(kvpzero, kvpset);
console.log(newArray);
结果:
[
{ key: '0', value: 'Zero' },
{ key: '1', value: 'One' },
{ key: '2', value: 'Two' },
{ key: '3', value: 'Three' },
{ key: '4', value: 'Four' },
{ key: '5', value: 'Five' },
{ key: '6', value: 'Six' },
{ key: '7', value: 'Seven' },
{ key: '8', value: 'Eight' },
{ key: '9', value: 'Nine' }
]
如果有更好的方法,我希望能知道我错过了什么。