Необходимый скелет кода для упрощения задачи приведен ниже.В принципе, могут быть различные типы Source
объектов.Для простоты в коде ниже показаны два типа источников: DirectSource
и IndirectSource
.Функция sourceAdapter()
принимает Source
и другие вспомогательные параметры.
В примере: если параметр key
отсутствует, Source
должно быть DirectSource
;если key
является одиночным строковым значением, то Source
должно быть IndirectSource
, и в обоих случаях код выполняет необходимые корректировки и возвращает объект DirectSource
.Если key
является массивом, предполагается, что Source
будет IndirectSource
, что также является возвращаемым значением функции.
type KeyMap<T> = { [key in keyof T]: number };
type DirectSource = {
value: number;
otherFieldsAndMethods: any;
};
type IndirectSource<T extends object> = {
kvMap: KeyMap<T>;
otherFieldsAndMethods: any;
};
type Source<T extends number | object> = T extends object ? IndirectSource<T> : DirectSource;
// overloads
function sourceAdapter(src: Source<number>): DirectSource;
function sourceAdapter<T extends object>(src: Source<T>, key: keyof T): DirectSource;
function sourceAdapter<T extends object>(src: Source<T>, key: (keyof T)[]): IndirectSource<T>;
function sourceAdapter<T extends number | object>(
src: Source<T>,
key?: keyof T | (keyof T)[]
): T extends object ? IndirectSource<T> : DirectSource {
if (key) { // According to function overloads Source must be an IndirectSource
if (key instanceof Array) { // Config and return IndirectSource
const kvMap = key.reduce((ac, s) => {
ac[s] = (src as any).kvMap[s];
return ac;
}, {} as any);
// ******Error here:
// Type 'T' does not satisfy the constraint 'object'.
let ret: IndirectSource<T> = {
kvMap,
otherFieldsAndMethods: src.otherFieldsAndMethods
};
return ret;
} else { // Config and return DirectSource
let directSource = {
otherFieldsAndMethods: src.otherFieldsAndMethods,
value: (src as IndirectSource<any>).kvMap[key],
};
return directSource; // ******Error here: assignability
}
} else { // Source is a DirectSource, simply return the src.
return src;
}
}
Строки, в которых возникают ошибки, представляют собойотмечены звездами. Это ссылка на игровую площадку.