Take this code as an example:
function isKeyOf<T extends {}>(
key: string, // this: string,
obj: T,
): key is keyof T {
return key in obj;
}
This works fine, but what if I want to do chaining (like an extension method)
In usage like this:
let key: string;
// ...
if (key.isKeyOf(obj)) {
obj[key] = value;
// ...
}
I have to do something like
// declare global {
interface /*Custom*/String {
isKeyOf<T extends object>(obj: T): this is { value: keyof T }
}
// }
But if I try:
CustomString.prototype.isKeyOf = function<T extends {}>(obj: T): this is keyof T {
return this in obj;
}
TS compiler won't let me use this
in type guard functions.
How to implement type narrowing in case that str in obj
infers str
is of type keyof obj
?
this
-like behavior, if you want.boolean
). Does that fully address the question? If so I'll write up an answer explaining. If not, what am I missing?