I have a type that defines a function's signature like so:
type TLoggerCallback = ((loggerMessageType: string, loggerErrorLevel: TLoggerLogLevel, object: object) => void)
In one class, I'd like to import TLoggerCallback
and define a new function signature starting from this one, narrowing down the object
parameter to a specific type of object, thus defining a new (e.g.) TClassLoggerCallback
defined like so:
type TClassLoggerCallback = ((loggerMessageType: string, loggerErrorLevel: TLoggerLogLevel, object: { prop1: string }) => void)
Please mind that object
should stay an object at all times; so I should be able to "override" its definition by defining a more specific object but I shouldn't, e.g., be able to make it a string.
How do I go about "overriding" (in this case by narrowing down) TLoggerCallback
's object
parameter like so?
The idea obviously is to have a generic logger callback type which can be narrowed down for each specific use case, in order to get the advantages of having the parameter more strictly typed (for the usual stuff, such as completion, errors etc...)
If that requires defining TLoggerCallback
as an interface in the first place, I'm perfectly fine with doing that.
Thanks!
CodePudding user response:
If I understand correctly, you want to keep TLoggerCallback
, but change the object
field type at will. You can achieve this with the use of a generic.
type TLoggerCallback<T extends Record<string,any>> = ((..., object: T) => void)
T extends Record<string,any>
ensures that only objects are passed as type arguments.
You can use it this way
type ClassType = { prop1: string }
const test: TLoggerCallback<ClassType> = (..., object: { prop1: string } ) => {}