The parameter Record<string, unknown>
, means you can pass in a object with no properties (like you do, where you pass {}
) but the callback you pass in requires proeprties on the first argument. So this is not type safe.
What you could do is make execCb
generic, so the parameter can be any type. THis also means you won't be able to pass in a concrete object in execCb
(at least not without a type assertion). You can for example pass it as an extra parameter to execCb
.
type Callback<T> = (data: T) => void
const execCb = <T extends Record<string, unknown>>(cb: Callback<T>, param: T) => {
cb(param)
}
type MyCallBackData = {
foo: string,
bar: number
}
const myCallback = (data: MyCallBackData) => {
// do something
}
execCb(myCallback, {
foo: "",
bar: 1
})
Playground Link
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…