#Type narrowing
17 messages · Page 1 of 1 (latest)
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:
...```
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;
}
ah, that works perfectly, thank you!
!resolved
fyi this is called a DU
https://www.typescriptlang.org/docs/handbook/2/narrowing.html#discriminated-unions
Understand how TypeScript uses JavaScript knowledge to reduce the amount of type syntax in your projects.
you could have Channel just have type: string in case you want to use extend it in the future
I knew there was a name for it -- thanks so much! I had forgotten what it was called
would typing if (message.channel.type == still give you a dropdown menu of possible values (guild, dm, etc) if you did it this way?
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
ah, I see
but then implementing classes aren't required to have the type field, which sort of is the point of having an interface in the first place
like technically you could also omit send() from Channel couldn't you?
right, i misread your usage a bit. you'd want type there yeah
if not all channels have that then yes, for example stage channels or category channels
(this is not really my use case -- I just used discord terms for the example)