Hur kan jag ange en explicit arraytyp utan att kopiera och klistra in dess värden i TypeScript?


Jag har en array:

const mediaFileKeys = ["mp3", "wave", "stems", "image"];

Och jag behöver att det har explicita värdetyper.

Så jag kopierade och klistrade in dess värden:

const mediaFileKeys: ["mp3", "wave", "stems", "image"] = ["mp3", "wave", "stems", "image"];

Finns det något sätt att göra det utan att behöva kopiera arrayvärdena?

Svar #1

Använd bara as const-påståendet:

const mediaFileKeys = ["mp3", "wave", "stems", "image"] as const;