0

My question is similar to this one, but with a twist. I want to create a string literal union type, but the values from the initial array come from a package (json data file), and are obtained through "require"

The most common scenario is like this :

const namesArr = ["John", "Lily", "Roy"] as const;
type Names = typeof namesArr[number]; // "John" | "Lily" | "Roy"

But my scenario is like this :

const namesArr = require('names-package');
type Names = typeof namesArr[number]; // "John" | "Lily" | "Roy"

My problem is that Typescript thinks that type "Names" is really "any".

const name:Names = "John"; //Visual studio code shows "name" as being of type "any".

I can see inside the package that the data comes from a basic Json file : index.json

[
  "John",
  "Lily",
  "Roy"
]

Is there anything I can do about it?

jeancallisti
  • 1,046
  • 1
  • 11
  • 21
  • 1
    Not unless `names-package` exposes more specific types than `any[]`. – jonrsharpe Oct 24 '22 at 13:21
  • As the next-best thing, I've skipped the external package altogether and instead copy-pasted the data into a local array of strings : ```const allMyStrings = ["John", "Lily"]``` . Visual Studio code still shows type ```Names``` as ```string[]``` when I hover, it's irritating. I don't know if it's just an intellisense thing and if I can trust the end-result. – jeancallisti Oct 24 '22 at 13:24
  • 1
    If you're willing to do that, copy the array into your own code, why not also add `as const` to get the more specific type? – jonrsharpe Oct 24 '22 at 13:42

0 Answers0