0

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'!
}));

1
  • I smell a XY problem Commented Aug 29, 2022 at 17:38

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.