英文:
How to add a custom field to an array in typescript
问题
我有一个数组:
const array = ["en-US", "en-GB", "en-AU"] as const;
我想要在这个数组中添加一个名为 default
的字段,以便像这样使用:
array.default;
而不是像这样使用:
array[0];
约束条件:不要失去数组的属性,并且仍然能够使用 find
和其他与数组相关的功能。我还需要正确的类型定义。
英文:
I have an array:
const array = ["en-US", "en-GB", "en-AU"] as const;
And I would like to add to this array a field default
in order to do something like:
array.default;
Instead of
array[0];
Constraints: Not loosing the property of an array and be able to still use find
and all other things propers to arrays. I also need the correct typing.
答案1
得分: 0
您可以使用Object.assign()方法来创建一个对象,通过复制一个对象的属性到另一个对象中合并它们。
在下面的示例中,创建了一个函数,该函数将一个default字段添加到一个对象中。Object.assign接受源对象和一个包含在第一个索引处设置值的对象字面量。返回值是具有新字段的原始源对象。
function addDefault<T extends readonly unknown[]>(src: T): T & { default: T[0] } {
return Object.assign(src, { default: src[0] });
}
const array = addDefault(["en-US", "en-GB", "en-AU"] as const);
console.log(array.default); // en-US
只要您像您的示例中一样使用不可变类型,这将正常工作。但是,如果您想要一个更灵活的版本,可以与可变数组一起使用,并且索引0处的值发生更改,则default仍将是索引0处的原始值。获取更新后的值的唯一方法是使用方法而不是字段。
下面的示例可以适用于更多类型,但default字段已更改为方法。
function addDefault<T extends { [x: number]: unknown }>(src: T): T & { default: T[0] } {
return Object.assign(src, { default() => src[0] );
}
const array = addDefault(["en-US", "en-GB", "en-AU"]);
array[0] = "fr-FR";
console.log(array.default()); // fr-FR
英文:
You can use Object.assign() to create an object that combines two objects by copying the properties of one to another.
In the example below a function is created that adds a default field to an object. Object.assign is passed the source object and an object literal with a property that is set a value at the first index. The returned value is the original source with the new field.
function addDefault<T extends readonly unknown[]>(src: T): T & { default: T[0] } {
return Object.assign(src, { default: src[0] });
}
const array = addDefault(["en-US", "en-GB", "en-AU"] as const);
console.log(array.default); // en-US
This will work fine as long as you're working with immutable types as in your example. However, if you wanted a more flexible version that works with mutable array, and the value at index 0 changes, then default will still be the original value at 0. The only way to get the updated value is to use a method instead instead of a field.
The example below will work on more types, but the default field has been changed to a method.
function addDefault<T extends { [x: number]: unknown }>(src: T): T & { default: T[0] } {
return Object.assign(src, { default() => src[0] );
}
const array = addDefault(["en-US", "en-GB", "en-AU"]);
array[0] = "fr-FR";
console.log(array.default()); // fr-FR
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论