【发布时间】:2019-09-16 14:46:52
【问题描述】:
打字稿 3.4.3
我想做这样的功能
exportObjectUnit({ a: 1, b: 2, c: 3, d: 4 }, ['b', 'c'])
输出
{ a: 1, d: 4 };
我不知道如何输入这个函数的返回类型
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;
};
如果我使用这个函数,返回值仍然有类型(第二个字符串数组参数除外)
---------编辑----
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;
};
我不知道如何返回。 从第一个对象中删除秒参数数组属性
-----------编辑 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)
【问题讨论】:
-
你为什么使用泛型?看来您确切地知道输入和输出是什么。泛型适用于必须使用不同类型的输入,然后输出相同类型的函数。在您的情况下,您不能为输入和输出类型写一个
interface或type吗? -
每次调用输入对象和输出对象都不一样(参数变化)
-
value(和returnValue)不总是object类型吗?您在value上使用Object.keys()并将returnValue初始化为{} -
我不明白你的评论
标签: javascript typescript