Allow skipping some generics when calling a function with multiple generics #10571
Comments
I would say covered by #2175 |
|
@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 ( This issue deals with the possibility of omitting some type parameters for automatic inference, while specifying others, not with defining fallback defaults. I also like @basarat's proposed |
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. |
@kitsonk You would still have to introduce an |
No... you could just skip them, like array destructuring: |
@kitsonk sure, coma-style skipping is an option too. However in your original post you argued for "default arguments" semantics, not array destructuring semantics. |
I personally find this very hard to read. specially with long argument list, something like #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. |
@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 |
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. |
@mhegazy that's one reason, but actually there's another one. 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! 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. |
Flowtype's equivalent is |
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 |
Same here. The situation I faced is to type the 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 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>({...}) |
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 |
Related: #1213 |
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 @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 |
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. |
That's brutal. This feature along with lazy evaluation of generics are the two biggest missing features in Typescript IMO. |
@DanielRosenwasser It's worth noting that Flow is working on implementing a similar concept (after they've deprecated |
hello.
and i want use a type that first arg of TStyles must be skiped:
but compiler get an error on , . |
Given the OP's example, could you do just: example<number>('thing', bool); ...and not have an 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 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 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. |
Is there any update for this? |
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 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 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 // 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" |
I consider the second form is a better option as it makes all inferred types available in the generic export function mapEnum<D extends string, infer S extends string>(value: S, object: {[K in S]: D}): D {
return object[value]
} |
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). |
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: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
{}
:Case 3 - the one that's interesting to this feature request - some can be inferred, some can't:
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
orinferred
type, so we could write:Or maybe even, if we only want to specify those up to a certain point:
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
The text was updated successfully, but these errors were encountered: