#Is it possible to define a `string` type that would be unique in an array of objects?

14 messages · Page 1 of 1 (latest)

naive fern
#

I'm curious to know if I can have a type that would be unique when used in an array.

Let's say I have this type:

type Book = {
   name: string
   author: string
}

const books: Book[] = [
   {
       name: 'Nature',
       author: 'Tom',
    },
   {
       name: 'Nature',
       author: 'Jake',
    },
]

I want Typescript to throw an error/warning on the name because the value Nature is duplicated in the array.

Is there a way to achieve that ?

subtle marsh
#

@naive fern I'm pretty sure there isn't a way to do that at the the type level.

naive fern
#

I see.. that's a bummer SilvPleads

naive fern
subtle marsh
#

@naive fern That's not really possible at the type level, either, no.

#

Some people will use nominal/branded types for that sort of thing, but for the most part, I'd just leave it at runtime checking.

naive fern
#

I have no idea what "nominal/branded" is

#

Also dunno what you mean by runtime checking

subtle marsh
#

@naive fern Runtime checking I just mean normal JS logic.

#

As opposed to TS which only 'exists' at compile-time.

naive fern
#

Yeah actually I wrote a JS function to manually go through the array and warn about the duplicate values, etc...

#

Are these features that I asked, on the TS roadmap, or they're not meant to be added... ?

subtle marsh
#

I don't know for sure, but I'd be a little surprised to see either.

#

"A string of a specific length" is kind of a hard thing to express at a type-level, outside of a language built for those kind of things - the technical term is "dependent types".