那就要用到类型世界里的参数----泛型了啦。
不考虑默认值问题会比较简单: TS Playground
function transDictToArray<TK extends string, TV extends string>(
dict: Record<string, unknown>,
keyLabel: TK,
valueLabel : TV
): Record<TK|TV, string>[] {
const arr: Record<TK|TV, string>[] = [];
for (const key in dict) {
if (Object.prototype.hasOwnProperty.call(dict, key)) {
const item = {
[keyLabel]: key,
[valueLabel]: dict[key] as string,
} as Record<TK|TV, string>;
arr.push(item);
}
}
return arr;
}
const arr = transDictToArray({a: 1, b: 2}, 'kkk', 'vvv');
let kkk = arr[0].kkk;
考虑默认参数的话,只能用重载实现了:
TS Playground
function transDictToArray<TK extends string, TV extends string>(
dict: Record<string, unknown>,
keyLabel: TK,
valueLabel : TV
): Record<TK|TV, string>[];
function transDictToArray<TK extends string>(
dict: Record<string, unknown>,
keyLabel: TK,
valueLabel?:'value'
): Record<TK|'value', string>[];
function transDictToArray(
dict: Record<string, unknown>,
keyLabel?: 'label',
valueLabel?:'value'
): Record<'label' |'value', string>[];
function transDictToArray(
dict: Record<string, unknown>,
keyLabel: string = 'label',
valueLabel : string = 'value'
): Record<string, string>[] {
const arr: Record<string, string>[] = [];
for (const key in dict) {
if (Object.prototype.hasOwnProperty.call(dict, key)) {
arr.push({
[keyLabel]: key,
[valueLabel]: dict[key] as string,
});
}
}
return arr;
}
transDictToArray({a: 1, b: 2}, 'kkk', 'vvv')[0].kkk;
transDictToArray({a: 1, b: 2}, 'kkk')[0].value;
transDictToArray({a: 1, b: 2})[0].label;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…