TYPESCRIPT 3.4.3
I want to make function like this
exportObjectUnit({ a: 1, b: 2, c: 3, d: 4 }, ['b', 'c'])
OUTPUT { a: 1, d: 4 };
I don't know how to typing this function's return type
export const exportObjectKey = <T, K extends keyof T>(value: T, exports: K[]) => {
const returnValue = {};
Object.keys(value)
.filter(key => {
if (exports.indexOf(key) !== -1) {
return false;
}
return true;
})
.map(key => {
returnValue[key] = value[key];
});
return returnValue as T;
};
If I use this function, return value still have types (With the exception of second string array parameter)
----------EDIT----------------
export const exportObjectKey = <T>(value: T, exports: Array<keyof T>) => {
const returnValue = {};
Object.keys(value)
.filter(key => {
if (exports.indexOf(key as keyof T) !== -1) {
return false;
}
return true;
})
.map(key => {
returnValue[key] = value[key];
});
return returnValue as T;
};
I don't know how to return. Removing seconds parameter array property from first object
-----------EDIT 2----------------
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export const exportObjectKey = <T, K extends keyof T>(value: T, omit: K): Omit<T, K> => {
delete value[omit];
return value;
};
export const exportObjectKeys = <T, K extends Array<keyof T>>(value: T, removes: K) =>
removes.reduce((object, key) => exportObjectKey(object, key), value);
// This is not perfect version
const a = { a: 1, b: 2, c: 3 };
const keyOmitOne = exportObjectKey(a, 'b');
// When I type keyOmitOne.
// Type definition available, It works (a, c)
// ------------------------------------------
// But, when I use exportObjectKeys
const b = { a: 1, b: 2, c: 3 };
const keyOmitArray = exportObjectKey(b, ['b', 'c']);
// I thought type definition works (a available)
// But there is no definition in b value)