#Static issue with user-defined type guard

1 messages · Page 1 of 1 (latest)

jolly carbon
#
export type Entity = {
   hasComponent<T>(componentName: string): this is T;
}

Hello- I'm getting an error here:
A 'this' type is available only in a non-static member of a class or interface.

How is the hasComponent method static? Doesn't hasComponent implicitly have this as an argument?
Or am I missing something entirely?

zinc shard
jolly carbon
#

Oh, right

zinc shard
#

and functions have a this parameter, not a this type

jolly carbon
#

yep 👍

zinc shard
jolly carbon
#

However the this is T idea would still work appropriately, right?

zinc shard
#

i guess the idea is that usually for types you dont really care about inheritance

#

if you convert it to an interface it should work fine

jolly carbon
#

awesome, thanks a lot for the help :)

zinc shard
#

you could try manually adding a this parameter, which might make typescript recognize that its a parameter name not the special this type?

#

i wouldn't know, i've never tried

jolly carbon
#

right, yeah I was just about to ask that.

vocal onyxBOT
jolly carbon
#

I'm wondering what happens if I mix and match types and interfaces. I'll have a play around :)

#

again- thanks a lot for the help

#

!resolved

vocal onyxBOT
zinc shard
#

nope :(

#

!ts

vocal onyxBOT
#
export type Entity = {
   hasComponent<T>(this: Entity, componentName: string): this is T;
//                                                       ^^^^
// A 'this' type is available only in a non-static member of a class or interface.
}
jolly carbon
#

huh weird

#

surely if you rename the this though

zinc shard
#

this is a special parameter

#

it doesnt actually exist

jolly carbon
#

I suspect the this won't be picked up as the special parameter then

#

yeah

zinc shard
#

yea

jolly carbon
#

I come from a lua background, so where I come from we don't really worry about this or self, everything is just a static function :p

zinc shard
#

i mean

#

you can still define methods

jolly carbon
#

In a type you mean?

zinc shard
#

function obj:method () end

jolly carbon
#

oh yeah yeah

#

but it's functionally equivalent to function obj.method(self) end

zinc shard
#

i do the very idiosyncratic local f = function () end though

jolly carbon
#

hah, yeah classic

zinc shard
#

in an effort to minimize the number of syntax constructs im using

#

not like its harder to maintain or anything so might as well, right?

#

and not like it's different semantically unlikecough JS

jolly carbon
#

haha yeah sure, each to their own! :)

jolly carbon
#

in hindsight it hurts readibility a tiny bit, but like, does it really matter that much?