The Wayback Machine - https://web.archive.org/web/20210119164123/https://github.com/Microsoft/TypeScript/issues/10571
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow skipping some generics when calling a function with multiple generics #10571

Open
niieani opened this issue Aug 26, 2016 · 50 comments · May be fixed by #26349
Open

Allow skipping some generics when calling a function with multiple generics #10571

niieani opened this issue Aug 26, 2016 · 50 comments · May be fixed by #26349

Comments

@niieani
Copy link

@niieani niieani commented Aug 26, 2016

Right now in TypeScript it's all or nothing when calling generic methods. You can either skip typing all the generics altogether and they will be inferred from the context (if possible), or you have to manually (re)define all of them. But the reality isn't black and white, there are also shades of gray, where we can infer types for some of the generic parameters, but not others. Currently those have to be unnecessarily verbose by forcing the programmer to explicitly restate them.

Take a look at these 3 cases:

Case 1 - everything can be inferred - no need to call the method with <> definition:

function case1<A, B, C>(a: A, b: B, c: C): A {}

example(1, '2', true);

Compiler knows that:
A is number
B is string
C is boolean


Case 2 - nothing can be inferred, so we need to state what A, B and C should be, otherwise they'll default to {}:

function case2<A, B, C>(): A {}

example<number, string, boolean>();

Case 3 - the one that's interesting to this feature request - some can be inferred, some can't:

function case3<A, B, C>(b: string, c: boolean): A {}

// incorrect type of A - left unspecified:
example('thing'); 

// correct, but unnecessarily verbose - we already know that 'thing' is a string and true is a bool
example<number, string, boolean>('thing', true);

Now, typing string, boolean in the above example isn't a big deal, but with complex scenarios, say with a method using 5 generics, where you can infer 4 of them, retyping them all seems overly verbose and prone to error.

It would be great if we could have some way to skip re-typing the types that can automatically be inferred. Something like a special auto or inferred type, so we could write:

example<number, auto, auto>('thing', bool);

Or maybe even, if we only want to specify those up to a certain point:

example<number>('thing', bool);

The above "short-hand" notation could perhaps be different to account for function overloads with different number of generics.

Having such a feature would solve newcomers encountering problems such as this one: http://stackoverflow.com/questions/38687965/typescript-generics-argument-type-inference/38688143

@mhegazy
Copy link
Contributor

@mhegazy mhegazy commented Aug 26, 2016

I would say covered by #2175

@basarat
Copy link
Contributor

@basarat basarat commented Aug 26, 2016

auto I would say * as auto might be a type name (unlikely but still). Also shorter 🌹

@niieani
Copy link
Author

@niieani niieani commented Aug 27, 2016

@mhegazy I don't think #2175 covers this. In fact, both propositions complement each other quite nicely. The proposed "Default generic type variables" extends the "all or nothing" notion of generic usage and deals with the way the class/function producer specifies them, not the way the class/function consumer uses them. In usage, you are still left with either omitting all generic parameters or specifying all explicitly. The only thing #2175 changes is the fallback type ({}) when it cannot be automatically inferred by the compiler.

This issue deals with the possibility of omitting some type parameters for automatic inference, while specifying others, not with defining fallback defaults.
Hope that's clearer.

I also like @basarat's proposed * instead of auto.

@kitsonk
Copy link
Contributor

@kitsonk kitsonk commented Aug 27, 2016

We already have a paradigm for passing arguments to functions, including default arguments in ES6+ in TypeScript/JavaScript. Why invent a new semantic? Why would generics just not follow the same semantics.

@niieani
Copy link
Author

@niieani niieani commented Aug 27, 2016

@kitsonk You would still have to introduce an undefined type for non-last arguments (in ES6+ this is how you would use the default on non-last arguments).
The proposed * / auto is just that -- without the ugly sounding undefined which is also a type, now that we have strict null checks.

@kitsonk
Copy link
Contributor

@kitsonk kitsonk commented Aug 27, 2016

No... you could just skip them, like array destructuring: < , , Bar>

@niieani
Copy link
Author

@niieani niieani commented Aug 27, 2016

@kitsonk sure, coma-style skipping is an option too. However in your original post you argued for "default arguments" semantics, not array destructuring semantics.
Ultimately I'm okay with either semantic, < , , Bar> or <*, *, Bar>.

@mhegazy
Copy link
Contributor

@mhegazy mhegazy commented Aug 29, 2016

I personally find this very hard to read. specially with long argument list, something like foo<, , ,A, , D>() was that right? or was it foo<, , ,A, D, >() .

#2175 puts this on the declaration. you have to decide as an interface author which type parameters are optional, and what are the defaults, and you put them at the end.

also note that generic type arguments is modeled after function arguments. it is illegal to call a function with missing arguments, or with less parameters than the signature requires.

@niieani
Copy link
Author

@niieani niieani commented Aug 29, 2016

@mhegazy the problem is as the interface author you cannot always reliably put them at the end. Sometimes you might need to force the use of the last argument, while the penultimate is inferred. That's why we need to be able to choose which are to be inferred - as the consumer.

Indeed it is illegal to call with missing arguments, that's why we're proposing an "infer" argument - equivalent of undefined - the empty space or *. You do make a point with coma skip being hard to read with long lists of arguments -- I'm going to back the * proposed by @basarat.

@kitsonk
Copy link
Contributor

@kitsonk kitsonk commented Aug 29, 2016

the problem is as the interface author you cannot always reliably put them at the end.

Can you provide an example, considering TypeScript allows overrides, where you feel this cannot be accomplished?

@mhegazy
Copy link
Contributor

@mhegazy mhegazy commented Aug 29, 2016

Can you provide an example, considering TypeScript allows overrides, where you feel this cannot be accomplished?

I would expect @niieani wants to keep the type parameter in the same order as the regular parameters. so in this sense it is not always possible to move them around if you do not control the actual function signatures.

@niieani
Copy link
Author

@niieani niieani commented Aug 29, 2016

@mhegazy that's one reason, but actually there's another one.
I came across this problem while writing type declarations for RethinkDB. The definitions are incredibly complex and I remember being unable to implement certain features exactly because of the fact that certain classes would have to use up to 4-8 generics (as a workaround, because of other TS limitations). Each generic type would be a pre-formed object based on the input T, so that we can keep track of the original(s) while transforming the object being passed through (notably the way RethinkDB's group() and ungroup() methods work).

The end-user only needs to be able to consume the methods by passing one or two generic arguments at most, not all of them -- the point is I don't want to burden the user from having to re-type all the generics that are an implementation detail. But ultimately non-last arguments are not a major problem for the end-user, it's my problem as the type-definition/library creator, as not being able to type only the specific one or two type parameters creates a maintenance nightmare!
Output of every single method would require me to type and re-type those same generic types over and over again, while most of them could be inferred and only some need manual adjustment in the output.

I don't remember the exact code example right now as I was working on the typings around February, but if I start working on it again, I'll post one here.

@niieani
Copy link
Author

@niieani niieani commented Dec 23, 2016

Flowtype's equivalent is * - existential type. Read this for reference.

@pocesar
Copy link

@pocesar pocesar commented Jan 3, 2017

skipping commas is something JS already has (inside destructuring and sparse arrays) would be nice to have as types. recently got struck by this problem with Redux Actions, it's really really really really hard to implement functional middleware typings when the resulting function is so deeply nested and you have to have 4-5 generics in the type declaration and must declare all of them manually if you decide to ever define any of them

@unional
Copy link
Contributor

@unional unional commented Jan 18, 2017

Same here. The situation I faced is to type the ExtJS's Ext.extend() method:

interface ExtendedClass<Config, Class, Override> extends Function {
  new (config: Config): Class & Override;
  superclass: Class;
}

declare class Ext {
  static extend<Config, Class, Override>(superclass: new(...args: any[])
    => Class, overrides: Override): ExtendedClass<Config, Class, Override>;
}

// optimal usage
interface MyActionConfig { ... }
const MyAction = Ext.extend<Ext.ActionConfig & MyActionConfig>(Ext.Action, { ... })

// actual usage
interface MyActionConfig { ... }
interface MyActionOverride { ... }
const myActionOverride: MyActionOverride = { ... }

const MyAction = Ext.extend<
  Ext.ActionConfig & MyActionConfig,
  Ext.Action,
  Ext.MyActionOverride>(Ext.Action, myActionOverride)

const myAction = new MyAction({ ... }) // { ... } is Ext.ActionConfig & MyActionConfig

Currently, I have to do a trade-off by giving up the ability to connect MyAction and MyActionConfig just to make it easier to author new class:

interface ExtendedClass<Class, Override> extends Function {
  new <Config>(config: Config): Class & Override;
  superclass: Class;
}

declare class Ext {
  static extend<Class, Override>(superclass: new(...args: any[])
    => Class, overrides: Override): ExtendedClass<Class, Override>;
}

interface MyActionConfig { ... }
const MyAction = Ext.extend(Ext.Action, { ... })

// Trade off: user of `MyAction` need to do this every time.
const myAction = new MyAction<Ext.ActionConfig & MyActionConfig>({...})
@unional
Copy link
Contributor

@unional unional commented Jan 19, 2017

Please ignore my last post. I'm able to simplify it. Here is what I got:

interface ExtendClass<Class> extends Function {
  superclass: Class;
}

declare class Ext {
  static extend<Class>(superclass: new(...args: any[])
    => any, overrides: Partial<Class>): Class & Ext.ExtendClass<Class>;
}

// usage
export interface MyAction extends Ext.Action {
  // You must define the constructor so that your class can be instantiated by:
  // `const action = new MyAction(...)`
  new (config: MyAction.Config): MyAction;
  // your custom properties and methods
}

export const MyAction = extend<MyAction>(Ext.Action, {
   // properties and methos exists in `MyAction`
})

export namespace MyAction {
  export type Config = Partial<Ext.ActionConfig> & {
    // Additional properties
  }
}

The only thing is that I can't restrict the superclass: new(...args: any[]) => any, but that's icing on the cake.

@niieani
Copy link
Author

@niieani niieani commented Feb 22, 2017

Related: #1213

@ghetolay
Copy link

@ghetolay ghetolay commented Mar 31, 2017

Here is another use case :

function actionBuilder<T, R extends string>(type: R | '') {
  return function(payload: T) {
    return {
      type: type,
      payload
    };
  };
}

//espected usage
const a = actionBuilder<number>('Action');
//Instead of
const a = actionBuilder<number, 'Action'>('Action');

// a would be of type
number => { type: 'Action', payload: number };

So while defining T is mandatory, we could totally infer R and avoid defining it aswell.

@mhegazy I tried with default generic :

function actionBuilder<T, R extends string = string>(type: R | '') {
  return function(arg: T) {
    return {
      type: type,
      payload: arg
    };
  };
}

const a = actionBuilder<number>('a')(3);

Here a.type was not inferred and got the default string type instead of the string literal a.
But look likes a combination of default generic type and #14400 would do.

@DanielRosenwasser
Copy link
Member

@DanielRosenwasser DanielRosenwasser commented Oct 30, 2018

I think seeing the last implementation has given us some pause on pursuing this. Additionally, we've been exploring other potential features that work with generics & inference (e.g. associated types) and we'd like to make sure everything plays nicely as well.

@clayne11
Copy link

@clayne11 clayne11 commented Oct 30, 2018

That's brutal. This feature along with lazy evaluation of generics are the two biggest missing features in Typescript IMO.

@niieani
Copy link
Author

@niieani niieani commented Oct 31, 2018

@DanielRosenwasser It's worth noting that Flow is working on implementing a similar concept (after they've deprecated * which worked slightly differently). They're using underscore (_) instead of (*), see their commit here: facebook/flow@fb23b93

@mdeljavan
Copy link

@mdeljavan mdeljavan commented Nov 12, 2018

hello.
i have same case that i want to skip first optional generic type but i can not do this. can you help me?
i have this types:

type TDefaultViewStyleKeys ={
  containerStyle: any
}
type TTextStyleKeys = {
  textStyle: any
}

export type TViewStyles<T> = {
  [key in keyof T]?: StyleProp<ViewStyle>
};
export type TTextStyle<T> = {
  [key in keyof T]?: StyleProp<TextStyle>
}

export type TStyles<ViewStyleKeys=TDefaultViewStyleKeys, TextStyleKeys = TTextStyleKeys> = TViewStyles<ViewStyleKeys> & TTextStyle<TextStyleKeys>

and i want use a type that first arg of TStyles must be skiped:

type TTextStyleKeys = {
  labelStyle: any,
  textInputStyle:any
}
type TStyleInput = TStyles < ,TTextStyleKeys>

but compiler get an error on , .
how do i solve this case?

@lukescott
Copy link

@lukescott lukescott commented Dec 18, 2018

Given the OP's example, could you do just:

example<number>('thing', bool);

...and not have an auto/_/* placeholder? Even if that is more restrictive, it solves a lot of use-cases.

This is a common use-case for me - converting one type to another. The source type can be inferred, but the destination cannot.

// utils file
export function mapEnum<D extends string, S extends string>(value: S, object: {[K in S]: D}): D  {
	return object[value]
}

// file that imports mapEnum
export function upgrade(element: TextHeading): Heading {
	const a = element.attributes
	return {
		// ... omitted other keys
                //
                // Heading.size expects "h1" | "h2"
                // TextHeading.attributes.headingSize has "big-heading" | "small-heading"
                //
                // mapEnum converts:
                // "big-heading" -> "h1"
                // "small-heading" -> "h2"
                //
                // throw: Expected 2 type arguments, but got 1.
		size: mapEnum<Heading["size"]>(a.headingSize, {
			"big-heading": "h1",
			"small-heading": "h2",
		}),
	}
}

...which requires me to change it to:

mapEnum<Heading["size"], TextHeading["attributes"]["headingSize"]>(a.headingSize, ...)
// OR
mapEnum<Heading["size"], typeof a.headingSize>(a.headingSize, ...)

...or make a compromise:

export function mapEnum<V extends string>(value: string, object: {[k: string]: V})  {
	return object[value]
}

...which makes the return "h1" | "h2" but make the keys string instead of "big-heading" | "small-heading" - so if you typo the source keys the compiler won't pick up the mistake.

I have tried something like this:

export function mapEnum<V extends string, O extends {[K in V]: O[V]}>(value: V, object: O): O[V]  {
	return object[value]
}

But O[V] is string. Unless I do this:

mapEnum(a.headingSize, {
	"big-heading": "h1" as "h1", // "h1" is assumed to be `string` without cast
	"small-heading": "h2" as "h2",
})

I also run into rubenlg's case with testing frameworks as well, with spyOn, as well as other unit testing methods. The use-case is very similar - the source type can be inferred, but the destination cannot. So you either have to specify both, or none - making you choose between verbose typing or less restrictive typing.

@kamilzielinskidev
Copy link

@kamilzielinskidev kamilzielinskidev commented Dec 26, 2019

Is there any update for this?

@dhoulb
Copy link

@dhoulb dhoulb commented Jan 8, 2020

@lukescott

I think what you suggested would be too much of a break from the current way it works (i.e. you must specify all generics or none, no middle ground).

But as a solution I loved the suggestion about using the = infer syntax as a default value. I think the resulting syntax would be super clean.

export function mapEnum<D extends string, S extends string = infer>(value: S, object: {[K in S]: D}): D  {
	return object[value]
}

Additionally this could provide some protection if the value could not be inferred (rather than the generic defaulting to any which is probably never what you want).

export function mapEnum<D extends string, S extends string = infer>(value: S | null, object: {[K in S]: D}): D  {
	return object[value]
}

mapEnum<number>(null, {}); // TS error "cannot infer generic S" or similar.

Another thought I'd had was an always inferred generic using infer S syntax, that would actually stop you setting it manually. I might be trying to push this too far now, but I think it'd round out this set of functionality nicely.

// Either this syntax.
export function mapEnum<D extends string, infer S extends string>(value: S, object: {[K in S]: D}): D  {
	return object[value]
}

// Or this syntax (I can't decide).
export function mapEnum<D extends string>(value: infer S extends string, object: {[K in S]: D}): D  {
	return object[value]
}

mapEnum<number, "b">("a", {}); // TS error "generic S cannot be set manually, it must be inferred"
@alvis
Copy link

@alvis alvis commented Apr 16, 2020

I consider the second form is a better option as it makes all inferred types available in the generic <> declaration. Otherwise, you don't know what the compiler has inferred.

export function mapEnum<D extends string, infer S extends string>(value: S, object: {[K in S]: D}): D  {
	return object[value]
}
@jedmao
Copy link
Contributor

@jedmao jedmao commented Jun 29, 2020

I can't tell you how many times I've needed this feature and had to do something super ugly to dodge the non-existence of it (e.g., creating a wrapper function that has a subset of the generic types).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Linked pull requests

Successfully merging a pull request may close this issue.

You can’t perform that action at this time.