给定:
interface GenericType<G> = {
objectKey: G
},
const convert = (arg: {[key: string]: GenericType<any>}) =>
Object.fromEntries(Object.entries(arg).map(([key, value]) => [key, value.objectKey])
const converted = convert({
foo: {objectKey: "hello world"}
bar: {objectKey: false}
})
// should return {foo: "hello world", bar: false}
我该如何键入它,以便TypeScript知道converted
的类型是{foo: string, bar: boolean}
?现在,我能得到的最好的结果(见这里)是TypeScript推断类型是{foo: unknown, bar: unknown}
。
您可以执行类似的操作
const convert = <T extends Record<string, {objectKey: any}>>(arg: T) =>
Object.fromEntries(Object.entries(arg).map(([key, value]) => [key, value.objectKey])) as {[O in keyof T] : T[O]['objectKey']}
const converted = convert({
foo: {objectKey: "hello world"},
bar: {objectKey: false}
})
// return {foo: string, bar: boolean}