want to create simple generic interface for function, that accepts interface of object and first argument is key of object and second is key2 of object by object[key].
Here my solution
type Test<T extends Object, K extends keyof T = keyof T, V extends keyof T[K] = keyof T[K]> = (key: K, key2: V) => void
Object
const convertFunctionsMap = {
ms: {
h: millisecondsToHours,
s: millisecondsToSeconds,
m: millisecondsToMinutes
},
s: {
h: secondsToHours,
ms: secondsToMilliseconds,
m: secondsToMinutes
},
m: {
ms: minutesToMilliseconds,
s: minutesToSeconds,
h: minutesToHours
},
h: {
ms: hoursToMilliseconds,
s: hoursToSeconds,
m: hoursToMinutes
}
}
But I got
CodeSandbox: https://codesandbox.io/s/empty-leaf-cuz51r?file=/src/index.ts
CodePudding user response:
i don't how to explain, but i know it works
interface Test<T> {
<K1 extends keyof T, K2 extends keyof T[K1]>(key: K1, key2: K2): void;
}
const convertFunctionsMap = {
ms: {
h: 1,
s: 2,
m: 3
},
s: {
h: 1,
ms: 2,
m: 3
},
m: {
ms: 1,
s: 2,
h: 3
},
h: {
ms: 1,
s: 2,
m: 3
}
}
const getIn2: Test<typeof convertFunctionsMap> = ()=> {}
getIn2('ms', 'h');