Boris Grunwald
Boris Grunwald

Reputation: 2722

Creating typescript type from union of two ReadOnly arrays

I have the following typescript code, where I define two read only arrays and then create a type based on the union of those two arrays. However, vscode does not give me any intellisense when I try to define a variable of type Note. Why is that? Is there a better to solution to what I am trying to achieve here?

const allNotes = ["A",
    "A#",
    "B",
    "C",
    "C#",
    "D",
    "D#",
    "E",
    "F",
    "F#",
    "G",
    "G#",] as const

const allNotesWithFlats = [
    "A",
    "Bb",
    "B",
    "C",
    "Db",
    "D",
    "Eb",
    "E",
    "F",
    "Gb",
    "G",
    "Ab"
]
type Note = typeof allNotes[number] | typeof allNotesWithFlats[number];

const n : Note = '' // No intellisense

Upvotes: 1

Views: 171

Answers (1)

blaumeise20
blaumeise20

Reputation: 2220

You forgot the as const by the second array:

const allNotes = ["A",
    "A#",
    "B",
    "C",
    "C#",
    "D",
    "D#",
    "E",
    "F",
    "F#",
    "G",
    "G#",] as const

const allNotesWithFlats = [
    "A",
    "Bb",
    "B",
    "C",
    "Db",
    "D",
    "Eb",
    "E",
    "F",
    "Gb",
    "G",
    "Ab"
] as const
type Note = typeof allNotes[number] | typeof allNotesWithFlats[number];

const n : Note = '' // No intellisense

That worked fine for me.

Upvotes: 3

Related Questions