const isType = <T>(type: string) => (obj: unknown): obj is T => toString.call(obj) === `[object ${type}]`
I know it's a function about judging types, but it uses a lot of arrows and I don't understand what the arrows at each stage mean
const isType = <T>(type: string) => (obj: unknown): obj is T
The first part indicates that the function accepts a parameter and returns a boolean value of type judgment
=> toString.call(obj) === `[object ${type}]`
what the latter part means
CodePudding user response:
Consider this simplified example:
function isType<T,>(type: string) {
return function (obj: unknown): obj is T {
return toString.call(obj) === `[object ${type}]`
}
}
const foo = isType('hello')([])
isType
is a function <T>(type: string) =>
which returns another function (obj: unknown): obj is T
. THis another function is a typescript custom typeguard
However, toString
is not a typeguard itself, hence, I' m not sure if this partial function/typeguard is useful
CodePudding user response:
Let's give it a try. Just to start with, I don't think this does what is supposed to do.
The function is returning another function, that will act as a type guard. That means that TS can use it to narrow types.
You can consider isType
as being a factory function.
You'll need to make 2 calls for this to actually work
- one to get a type guard
- to actually call the type guard