Imagine I am working with three unique types (and one union type)
type Alpha = {
type: 'a'
title: string
description: string
}
type Beta = {
type: 'b'
title: string
}
type Charlie = {
type: 'c'
description: string
}
type Delta = Alpha | Beta | Charlie
I understand that proper type inference can be achieved using the === operator
function monitor(t: Delta) {
if (t.type === 'a' || t.type === 'b') console.log(t.title) // no issues here
if (t.type === 'a' || t.type === 'c') console.log(t.description) // no issues here
}
But, is it feasible to create a utility function like this:
function matches<T extends { type: string }>(t: T, types: T['type'][]) : boolean {
return types.includes(t.type)
}
So that I can perform the following without any errors?
function monitor(t: Delta) {
if (matches(t, ['a', 'b'])) console.log(t.title) // Property 'title' does not exist on type Delta
if (matches(t, ['a', 'c'])) console.log(t.description) // Property 'description' does not exist on type Delta
}