I have an interface defined as follows. It is part of a reusable NPM module. All works fine within the module, my unit tests work and I can create settings using [ "value" ]
export interface Settings {
nonEmptyArrayProperty: [string, ...string[]]
}
However I have another module which imports this package and I am trying to define settings from within it. I get the following error:
Type 'string[]' is not assignable to type '[string, ...string[]]'.
My settings are in a js file but are identical in terms of property names:
export const SETTINGS= {
nonEmptyArrayProperty: ["value1", "value"],
};
One thing to note is I am using the spread operator to convert the JS settings to the Settings interface defined in my library.
How do I assign a string[] to [string, ...string[]]?
The reason typescript doesn't allow this is because the type [string, [...string]] means that the value contains at least one string, while string[] can contain 0. So when it comes to the line of assignment, typescript only knows it's a string[], so it thinks it might be empty (event if it's obvious to us that it's not).
If you specify the type of the variable you assign to the settings object beforehand, you won't come into this trouble. In typescript, this means you can do the following when assigning the variable:
const nonEmptyArray = ["value1", "value"] as const;
But if you do (as pointed out in the comments) get the variable from an untyped javascript file, you'll have to be more specific with the type, as follows:
export const SETTINGS= {
nonEmptyArrayProperty: nonEmptyArray as [string, ...string[]],
};