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
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 & MyActionConfigCurrently, 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 |
|
#2175 |
|
It's been 5 years and still this important feature is missing. |
|
Wait until you find out what's missing from C! |
|
is a solution to change the syntax so that we can support named generics instead of ordered generics. Just like a function could take named parameters |
|
I have this example were I need to infer the second generic type passed to interface Flags {
study_plan_setup_button_text: 'original' | 'variation1';
feature_driving_enabled: boolean;
}
type ToUnion<T extends Record<keyof T, unknown>> = T[keyof T]
type FlagRequest<T extends Partial<Record<keyof T, unknown>>> = ToUnion<{
[Key in keyof T]: { key: Key, defaultValue: T[Key], activate?: boolean }
}>
interface UseFlagshipParams<T extends Record<keyof T, unknown>> {
modifications: {
requested: FlagRequest<T>[]
}
}
interface UseFlagshipOutput<T extends Record<keyof T, unknown>, Params extends UseFlagshipParams<T>> {
modifications: {
[Key in Params['modifications']['requested'][number]['key']]: T[Key]
},
}
function useFlagship<T extends Record<keyof T, unknown>, Params extends UseFlagshipParams<T>>(params: Params): UseFlagshipOutput<T, Params> {
// Some code here
return { modifications: {} } as any;
}
const { modifications } = useFlagship<Flags>({
modifications: {
requested: [
{
key: 'feature_driving_enabled',
defaultValue: false
},
{
key: 'study_plan_setup_button_text',
defaultValue: 'original'
}
]
}
}); |
|
@achan-godaddy I really like your idea about named generics. I think this would solve many problems in libraries which heavily depend on generics like |
|
Here is another use case:
import { AxiosError } from 'axios';
import { QueryFunction, QueryKey, useQuery, UseQueryOptions } from 'react-query';
// TODO: make other generic auto-infer when GAcceptedParams is specified. (Now it's all or nothing, specifying one with turn off auto-inference)
type TUseQueryOptions<
GResponseData,
GError = unknown,
GSelectedData = GResponseData,
GQueryKey extends QueryKey = QueryKey,
> = Omit<UseQueryOptions<GResponseData, GError, GSelectedData, GQueryKey>, 'queryKey' | 'queryFn'>;
export const generateQueryHook =
<GAcceptedParams, GResponseData, GOriginQueryKey extends string = string>(
originQueryKey: GOriginQueryKey,
queryFunction: QueryFunction<
GResponseData,
[first: GOriginQueryKey, second?: GAcceptedParams]
>,
) =>
<GSelectedData = GResponseData>(arg?: {
params?: Record<string, unknown> & GAcceptedParams;
options?: TUseQueryOptions<
GResponseData,
AxiosError,
GSelectedData,
[first: GOriginQueryKey, second?: Record<string, unknown> & GAcceptedParams]
>;
}) =>
useQuery<
GResponseData,
AxiosError,
GSelectedData,
[first: GOriginQueryKey, second?: Record<string, unknown> & GAcceptedParams]
>([originQueryKey, arg?.params], queryFunction, arg?.options);Generally, Currently, when I want to specify |
|
Another year passed without enough attention to this very important feature(especially for library maintainers!) |
|
Why is this feature still ignored, we really need it! I even can't do a simple type mapping ... interface TestType {
something: string;
other: number;
}
function func<T, K extends keyof T = keyof T>(key: K, arg: T[K]) { // Here didn't work
// do something
}
// func<TestType>( should auto complete with 'something' or 'other', and arg should be the right type |
function test<A, B>(param1: A, param2: B): B {
return param2;
}
/* Wanted two type arguments, 1 passed */
/* infer, auto, * or ? doesn't works to infer the generic type */
const value13ShouldBeNumber = test<string>('hello', 13) // value13ShouldBeNumber: expected: number, gets: unknownThird week learning and using TS and i need this feature... |
|
the upcoming typescript version may have a fix for this
|
|
I really hope I don't have to use that syntax to write my types, the only problem is that TS doesn't infer the generics, just implement something like: declare function test<A, B | infer>(param1: A, param2: B): B; |
"upcoming"? Hah! This PR has been open for 6 years now. |
|
@Ranguna |
|
@btoo You've missed the point of this issue. I'll illustrate with Case 3 from the original post: function case3<A, B, C>(b: B, c: C): 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);We'd like to write one of example<number>('thing', true);
example<number, _, _>('thing', true);
example<number, *, *>('thing', true);
example<number, infer, infer>('thing', true);
example<number, auto, auto>('thing', true);
example<A: number>('thing', true);You're suggesting we write which is even more verbose than the workaround that exists.
|
|
Still waiting for this feature and for now this could be a solution if you only have one required type parameter and lots of inferred type parameters: |
|
Still waiting for this feature. So sad. |
niieani commentedAug 26, 2016
•
edited
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, booleanin 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
autoorinferredtype, 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: