If I have an array for this sake ['test', 'test2', 'test3'], I'm adding aliases to it using Object.defineProperty() that are defined in a different array ['a', 'b', 'c'].
Here is my current (shortened) example that does not allow me to access the defined property on the returned array.
How can I have typescript recognise that there are defined properties on this array that match the values of the array ['a', 'b', 'c']?
const aliasArr = ['a', 'b', 'c'];
const applyAliases = <Alias extends string[], Values extends any[]>(aliases: Alias) => (arr: Values) => {
const definition = [...arr];
aliases.forEach((key, i) =>
Object.defineProperty(definition, key, {
enumerable: false,
get(): Values[number] {
return this[i];
},
})
);
return definition as typeof arr & { [P in keyof Alias]: Values[number] };
};
const applied = applyAliases<typeof aliasArr, string[]>(aliasArr)(['test', 'test2', 'test3']);
const test = applied.a // Error, property 'a' does not exist on type string[]
[P in keyof Alias]to[key in Alias[number]]fixes this. However I feel that this is still not a good solution asapplied.xdoes not throw an error.