#Type narrowing

17 messages · Page 1 of 1 (latest)

meager blade
#

How can I take an interface type and narrow it down to the specific class so I can access class-specific properties?

For example: how can I make it so that channel.type == 'guild' narrows the type from Channel to GuildChannel so I can access guild-specific properties?

old crestBOT
#
p.e.t.e#0

Preview:```ts
// @strictPropertyInitialization: false
interface Channel {
type: 'guild' | 'dm';
cache: Message[];
send(msg: String): void;
}

class GuildChannel implements Channel {
type: 'guild';
cache: Message[];
send(msg: String): void { }

// guild-specific properties:

...```

strange flax
#

the type of your channel property in the Message class should be a union of GuildChannel and DMChannel
you could make a helper type like this:```ts
type AnyChannel = GuildChannel | DMChannel

class Message {
channel: AnyChannel;
}

meager blade
#

!resolved

chilly sparrow
#

you could have Channel just have type: string in case you want to use extend it in the future

meager blade
meager blade
chilly sparrow
#

yes, because Channel would just be the base for extension, not in the actual structure (which would be AnyChannel)

#

you could also just omit type from Channel

meager blade
#

like technically you could also omit send() from Channel couldn't you?

chilly sparrow
chilly sparrow
meager blade
#

(this is not really my use case -- I just used discord terms for the example)