Can an array be typed in TypeScript to require at least one or more strings at any index, with any extra elements being numbers?
type NumberArrayWithAtleastOneString = [...(number[] | string)[], string]
const a: NumberArrayWithAtleastOneString = [1,'hello',3] // should work
const b: NumberArrayWithAtleastOneString = ['hello', 3, 'world'] // should work
const d: NumberArrayWithAtleastOneString = ['hello'] // should work
const c: NumberArrayWithAtleastOneString = [1,2,3] // should fail
const e: NumberArrayWithAtleastOneString = [] // should fail
Despite setting the correct types for the variables, all of them raise an error upon compilation. For example, const a
gives the following alert:
Type '[number, string, number]' is not assignable to type 'NumberArrayWithAtleastOneString'.
Type at positions 0 through 1 in source is not compatible with type at position 0 in target.
Type 'number' is not assignable to type 'string | number[]'.ts(2322)
What would be the correct way to annotate this in TypeScript, or is it not possible?