5

I have the following function:

type SomeType<T> = Record<string, T>;
declare function test<T>(...args: SomeType<T>[]): T;

I would like to call it like that (a should be of type number|string):

const a = test({a: 3}, {b: "as"});

but that way I get an error: Type 'string' is not assignable to type 'number'. can I make this work without explicitly passing the generic argument number|string or using conditional types?

Playground

3
  • I'm fairly sure you're stuck with writing const a = test<string|number>({a: 3}, {b: "as"});, but not sure enough to make it an answer. :-) Commented Jun 5, 2021 at 8:36
  • oh yeah sorry, i forgot that in my question i dont want to explicitly add the generic on every call. Why cant typescript not just infer it as a union type. I mean its possible as i suggested using conditional types (as i have shown in the playground, but thats also really messy) Commented Jun 5, 2021 at 8:38
  • 1
    Don't worry, your question pretty strongly implied you didn't want to do that. :-) It's just I think you're stuck with it. TypeScript only goes so far with inference. Commented Jun 5, 2021 at 8:40

1 Answer 1

1

Variadic tuples might help:

declare function test<T extends any[]>(...args: [...T]): T;

const a = test({ a: 3 }, { b: "as" });
Sign up to request clarification or add additional context in comments.

2 Comments

Just because it works, i wouldn't pass this solution to any production code because any, really means any typescriptlang.org/docs/handbook/2/everyday-types.html#any
@ArtemVadimovichSolovev That was just to show how it could be accomplished, of course you might write extends Record<whatever> suits their need

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.