#Type array so that find does not return undefined

13 messages · Page 1 of 1 (latest)

half portal
#

Is it possible to type an array where the items match a string literal union so that .find will never return undefined. For example:

const COLUMNS = ['id', 'name', 'date'] as const
type COLUMN = (typeof COLUMNS)[number]

const columns = [ { name: 'id', databaseName: 'FOOBAR_ID' }, { name: 'name', databaseName: 'FOOBAR_NAME', } { name: 'date', databaseName: 'FOOBAR_DATE" } ]

// This is of type { name: string, databaseName: string } | undefined
// and ideally it wouldn't be undefined since name is type COLUMN
const getColumn = (name: COLUMN) => columns.find((column) => column.name === name)
bronze raven
#

you can use the ! operator

half portal
#

yea I thought about that, but isn't it considered "hacky" ? lol

bronze raven
#

no, casts are no hacky when used right

#

if you know stuff better than the compiler, then it's the only way to tell it about it

half portal
#

true, I was just hoping there was a "proper" way to do it

bronze raven
#

otherwise yes, that would be unsafe

half portal
#

Is there a way to actually type columns so that if COLUMNS changes, it warns if its missing or has extra entries?

bronze raven
#

nope, not when using arrays at least

#

would be possible, but using objects

#

(with Record<COLUMN, > and some transform)