#javascript #typescript #generics
Вопрос:
Мне нужно выполнить некоторые преобразования в объекте машинописи, сохраняя при этом его полную форму.
Итак, у меня есть объект:
const simpleObject = {
one: () => ({}),
two: (a: number) => ({ a }),
};
type SimpleObject<K, V> = {
[P in keyof K]: V; // Not sure how to type V correctly to be a function that takes any arguments and outputs an object
};
где значения являются универсальными функциями, выводящими объект.
Мне нужно выполнить некоторые преобразования над объектом, чтобы:
type AugmentedObject<K, V> = {
[P in keyof K]: V; // again, typing of V is not correct here, it should be a generic function that outputs an object
};
function augmentObject<K, V>(simpleObject: SimpleObject<K, V>): AugmentedObject<K, V> {
// perform some transformation
// ...
return simpleObject;
}
augmentObject(simpleObject).one; // the type should resolve to a () => object
augmentObject(simpleObject).two; // the type should resolve to (a: number) => object
Я не могу понять, как поддерживать правильный ввод для one
или two
, поскольку я не могу понять, как в общем передать функцию
Ответ №1:
Я не уверен, что это то решение, которое вы ищете. Хотя окончательные типы имеют именно ту форму, которую вы от них ожидаете.
const simpleObject = {
one: () => ({}),
two: (a: number) => ({ a }),
};
type SimpleObject
= { [K in string | number | symbol]: (...args: any[]) => object }
function augmentObject<T extends SimpleObject>(simpleObject: T): T {
// perform some transformation
// ...
return simpleObject;
}
const a = augmentObject(simpleObject)
type One = typeof a.one // type One = () => {}
type Two = typeof a.two // type Two = (a: number) => { a: number }