[FIXED] How to provide 'as const' to string array in function argument

Issue

How can I provide a generic string array to a function argument and use the generic type in the other function argument?

I want to achieve something like this below:

type Custom<T> = {
  hello: string;
  world: T;
};

declare function builder<T extends readonly string[]>(
  input: T,
  arg: () => Custom<T>,
): void


builder(['hello'] as const, () => ({
    hello: 'some text',
    world: ['1', '2', '3'], // <-- This should fail, as it's not 'hello'!
}));

Solution

You don’t really need to use as const here. You can use variadic tuple types to infer input as a string tuple.

type Custom<T extends string[]> = {
  hello: string;
  world: [...T];
};

declare function builder<T extends string[]>(
  input: [...T],
  arg: () => Custom<T>,
): void

Or you could use T as just a string type and type input and world as T[].

type Custom<T extends string> = {
  hello: string;
  world: T[];
};

declare function builder<T extends string>(
  input: T[],
  arg: () => Custom<T>,
): void

Answered By – Tobias S.

Answer Checked By – Katrina (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published