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 · 46 comments

Comments

@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

This comment has been minimized.

Contributor

mhegazy commented Aug 26, 2016

I would say covered by #2175

@basarat

This comment has been minimized.

Contributor

basarat commented Aug 26, 2016

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

@niieani

This comment has been minimized.

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

This comment has been minimized.

Contributor

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

This comment has been minimized.

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

This comment has been minimized.

Contributor

kitsonk commented Aug 27, 2016

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

@niieani

This comment has been minimized.

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

This comment has been minimized.

Contributor

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

This comment has been minimized.

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

This comment has been minimized.

Contributor

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

This comment has been minimized.

Contributor

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

This comment has been minimized.

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

This comment has been minimized.

niieani commented Dec 23, 2016

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

@pocesar

This comment has been minimized.

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

This comment has been minimized.

Contributor

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

This comment has been minimized.

Contributor

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

This comment has been minimized.

niieani commented Feb 22, 2017

Related: #1213

@ghetolay

This comment has been minimized.

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.

@kgtkr

This comment has been minimized.

kgtkr commented Mar 4, 2018

@NeoLegends
* should be used instead of _

@NeoLegends

This comment has been minimized.

NeoLegends commented Mar 4, 2018

IMO the underscore conveys the meaning of existential types (a la „Please deduce existing type here“) better than the star, because the star looks like „any type can fit here“ (which is not true). But lets leave the bikeshedding for later when the semantics of the feature have been thought through.

@appsforartists

This comment has been minimized.

appsforartists commented Mar 4, 2018

Maybe github needs a 🚲 reaction.

@weswigham

This comment has been minimized.

Member

weswigham commented Mar 7, 2018

For anyone watching this: I have a candidate implementation for this available in #22368 leveraging the infer T types that were added alongside conditional types, and would love to know how it matches up against your needs/expectations.

@banxi1988

This comment has been minimized.

banxi1988 commented May 28, 2018

well, seems, I'll need to wait TypeScript 3.0.
I have encounter such a situation,
because I want to promisify some callback style function. so I write some code like this:

export function promisify<P extends wx.BaseOptions, R>(
    fun: (options: P) => any
  ): ((options: P) => Promise<R>) {
    function newFun(options: P): Promise<R> {
      return new Promise(function(resolve, reject) {
        options.success = res => {
          resolve(res);
        };
        options.fail = () => {
          reject();
        };
        fun(options);
      });
    }
    return newFun;
  }

  export const login = promisify<wx.LoginOptions, wx.LoginResponse>(wx.login);

And aboviously the first generic type wx.LoginOptions can be inferred from wx.login function.

@DanielRosenwasser

This comment has been minimized.

Member

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

This comment has been minimized.

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.

@ohjames

This comment has been minimized.

ohjames commented Oct 31, 2018

And so a decade old design mistake from C# (C++ had partial type parameter inference from before) continues to infect TypeScript and our TS projects with excessive boilerplate and reduced type safety. Ah well, at least we have a better type system than Dart ;) Hope this doesn't take another few years to get over the finish line.

@niieani

This comment has been minimized.

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

This comment has been minimized.

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?

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