#Type guard on class property

14 messages ยท Page 1 of 1 (latest)

compact narwhal
#

Anyone knows how to get a type guard for a class property ?

wispy deltaBOT
#
elliotyoyo#0

Preview:```ts
class AnimalFriend {}

class Animal {
private friend: AnimalFriend | null = null

// this['friend'] is AnimalFriend ??
private hasFriend() {
return typeof this.friend !== null
}

private doSomething() {
if (this.hasFriend()) {
const f = this.friend
...```

round umbra
#

@compact narwhal The general syntax is:

private hasFriend(): this is { friend: AnimalFriend } {
    return typeof this.friend !== null;
}
#

But it appears this doesn't work with private properties.

#

I'm not sure there's a way to do this with private properties. I would suggest just getting the friend and checking if it's null, rather than trying to narrow hasFriend

compact narwhal
round umbra
#

Yup, #private is real ECMAScript private and just cannot be accessed outside of the class.

compact narwhal
wispy deltaBOT
#
elliotyoyo#0

Preview:```ts
class AnimalFriend {}

class Animal {
hasFriend: boolean = false
friend: AnimalFriend | null = null

/*
// this['friend'] is AnimalFriend ??
private hasFriend() {
return typeof this.friend !== null;
}
*/

private doSomething() {
if (this.hasFriend)
...```

compact narwhal
#

Maybe I would have to create an interface to type the class ? If fee like this is doable on interfaces

round umbra
#

I just wouldn't try to use this as a type-guard. Doing this kind of stuff with classes is generally fairly awkward.

#

If you were doing pure objects you could do something like:

type Animal = 
   | { hasFriend: true, friend: AnimalFriend }
   | { hasFriend: false }

but even that seems a bit redundant compared to just checking if animal.friend is null.

compact narwhal
#

Alright, makes sense.
This case is a simplification tho, hasFriend could be doesMySuperLongArrayHasAnObjectWhichNameIsImportant and recomputing it each time isn't performant

#

But well, you can't make magic with typing, in my case I I'll just check for null each time ๐Ÿ™‚ Thx a lot for the response!