Re:Adding type safety to object IDs in TypeScript
by int_19h on Tuesday January 30, 2024 @06:18PM
(#39197355)
You shouldn't need to write this kind of thing manually for every such type.
[ Parent
| on HN ]
Re:Adding type safety to object IDs in TypeScript
by ht85 on Wednesday January 31, 2024 @04:46AM
(#39201880)
function is<T extends string>(value: string, prefix: T): value is `${typeof prefix}_${string}` {
return value.startsWith(`${prefix}_`)
}
You can now do `is(id, 'user')`.If you do that often you probably want to create separate functions, e.g.:
function isFactory<T extends string>(prefix: T) {
return (value: string) => is(value, prefix)
}
const isUser = isFactory('user')
const isOrder = isFactory('order')
Not too bad.