#Type guard on class property
14 messages ยท Page 1 of 1 (latest)
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
...```
@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
Thanks for the reply, didn't think I could turn the guard in the other way ๐
Renaming the field to #friend kinda works, but:
- the property isn't "officially" private.
- I get a warning :
Private identifiers are not allowed outside class bodies.
Yup, #private is real ECMAScript private and just cannot be accessed outside of the class.
Do you know if there is a way to to something similar with another hasFriend property ?
The idea is to defined the friend property based on hasFriend
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)
...```
Maybe I would have to create an interface to type the class ? If fee like this is doable on interfaces
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.
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!