【发布时间】:2021-04-20 14:46:23
【问题描述】:
当我交换对象键值时,函数的返回类型是 { [x: string]: value } instedof const key.
游乐场here
interface IObj {
[key: string]: string;
};
const swapFn = <T extends IObj>(obj: T) => {
const res = {} as { [K in T[keyof T]]: keyof T };
Object.entries(obj).forEach(([key, value]) => {
res[value as T[keyof T]] = key;
});
return res;
}
// return type should be:
// {
// aaa: 'a',
// bbb: 'b',
// } insted of {
// [x: string]: "a" | "b";
// }
const result = swapFn({
a: 'aaa',
b: 'bbb',
});
【问题讨论】:
-
swapFn的返回类型声明了一个合约,即键是值类型——在你的情况下是字符串,每个键的值都是键类型,要么是“a " 或 "b"。
标签: typescript typescript-generics