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

Implement partial type argument inference using the _ sigil #26349

Open
wants to merge 9 commits into
base: main
Choose a base branch
from

Conversation

weswigham
Copy link
Member

@weswigham weswigham commented Aug 10, 2018

In this PR, we allow the _ sigil to appear in type argument lists in expression positions as a placeholder for locations where you would like inference to occur:

const instance = new Foo<_, string>(0, "");
const result = foo<_, string>(0, "");
const tagged = tag<_, string>`tags ${12} ${""}`;
const jsx = <Component<_, string> x={12} y="" cb={props => void (props.x.toFixed() + props.y.toUpperCase())} />;

This allows users to override a variable in a list of defaulted ones without actually explicitly providing the rest or allow a type variable to be inferred from another provided one.

Implements #26242.
Supersedes #23696.

Fixes #20122.
Fixes #10571.

Technically, this prevents you from passing a type named _ as a type argument (we do not reserve _ in general and don't think we need to). Our suggested workaround is simply to rename or alias the type you wish to pass. Eg,

interface _ { (): UnderscoreStatic; }

foo<_>(); // bad - triggers partial type inference, instead:

type Underscore = _;
foo<Underscore>(); // good

we did a quick check over at big ts query, and didn't find any public projects which passed a type named _ as a type argument in an expression/inference position, so it seems like a relatively safe care-out to make.

Prior work for the _ sigil for partial inference includes flow and f#, so it should end up being pretty familiar.

@alfaproject
Copy link

Why write infer explicitly? Could we do like destructuring? <, string> instead of <infer, string>

By default, it would infer.

@weswigham
Copy link
Member Author

@alfaproject I wrote my rationale down in #26242

@jwbay
Copy link
Contributor

jwbay commented Aug 14, 2018

Would this PR enable this scenario? I didn't see a test quite like it. Basically extracting an inferred type parameter from a specified type parameter.

type Box<T> = { value: T };

type HasBoxedNumber = Box<number>;

declare function foo<T extends Box<S>, S>(arg: T): S;

declare const hbn: HasBoxedNumber;

foo<HasBoxedNumber, infer>(hbn).toFixed();

@weswigham
Copy link
Member Author

Based on the design meeting feedback, this has been swapped to variant 2 from the proposal - using the * sigil as a placeholder for inference. We'll need updates to our tmlanguage to get syntax highlighting right (although we already parsed * in type positions for jsdoc, so we probably should have already).

sheetalkamat added a commit to microsoft/TypeScript-TmLanguage that referenced this pull request Aug 17, 2018
@weswigham
Copy link
Member Author

Would this PR enable this scenario? I didn't see a test quite like it. Basically extracting an inferred type parameter from a specified type parameter.

As is, no. Other type parameters (supplied or no) are not currently inference sites for a type parameter. We could enable it here (just by performing some extra inferType calls between the supplied types and their parameters' constraints), probably, but... should we? @ahejlsberg you have an opinion here?

@ahejlsberg
Copy link
Member

@ahejlsberg you have an opinion here?

I don't think we want constraints to be inference sites, at least not without some explicit indication. At some point we might consider allowing infer declarations in type parameter lists just as we do in conditional types:

type Unbox<T extends Box<infer U>> = U;

Though you can get pretty much the same effect with conditional types:

type Unbox<T extends Box<any>> = T extends Box<infer U> ? U : never;

@weswigham
Copy link
Member Author

Alright, I'll leave this as is then and just mention that it's available as a branch if we ever change our minds in the future.

@weswigham weswigham changed the title Implement partial type argument inference using the infer keyword Implement partial type argument inference using the * sigil Aug 17, 2018
@treybrisbane
Copy link

treybrisbane commented Aug 18, 2018

@weswigham It seems inconsistent (and kinda strange) to use the * sigil for this when we already use the infer keyword to denote explicit type inference...

type Tagged<O extends object, T> = O & { __tag: T };

// "Infer a type, and make it available under the alias 'T'"
declare function getTag<O extends Tagged<any, any>>(object: O): O extends Tagged<any, infer T> ? T : never;

// "Infer a type, and make it available to 'getTag' under the alias at the first type position"
getTag<infer>({ foo: string, __tag: 'bar' })
// => 'bar'

This seems like an obvious syntactic duality to me... What was the reason you instead decided to go with *?

@RyanCavanaugh
Copy link
Member

The existing infer T keyword produces a new binding for T; this wouldn't be available in argument positions (e.g. you can't write getFoo<infer T, T>()). Having the infer keyword have arity 1 in conditional types and arity 0 in type argument positions seems like a decrease in overall consistency rather than an increase.

@KyleDavidE
Copy link

It would probably be nice to be able to declare infer on the functions, ex: function foo<A, B = infer>(b: B, c: SomeComplexType<A,B>): SomeOtherComplexType<A,B>

@treybrisbane
Copy link

@RyanCavanaugh

Having the infer keyword have arity 1 in conditional types and arity 0 in type argument positions seems like a decrease in overall consistency rather than an increase.

Thanks for the response. :)

Fair enough, but I'd argue that this decrease in consistency is far less than that of introducing an entirely new sigil for this purpose. Is there really a benefit to users in using such a radically different syntax for something whose only difference to infer T is the arity?

@treybrisbane
Copy link

Something else to consider is that TypeScript supports JSDoc, and * in JSDoc means any. I'm not sure it's a good idea to reuse a symbol that means any in one context for something that means "please infer this type for me" in another context.

If we're concerned about making operators/keywords context-sensitive, then again it seems like making infer context-sensitive is far less of an evil than doing the same for *.

@insidewhy
Copy link

insidewhy commented Aug 31, 2018

I don't mind * as it jives with flow. Users of typescript can just avoid * in jsdoc and always use any for the purpose easily enough?

I'd also like to see this:

const instance = new Blah<T, **>(1, 'b', false, new Date())

I have a class that bundles many string literal types and I have to enumerate them all at every callsite even when I'm using the code from this branch. Everytime I add a new string literal I have to update every single callsite which is a massive drag ;)

@insidewhy
Copy link

Consider:

type LiteralMap<S1 extends string, S2 extends string, S3 extends string> = {
  item1: S1,
  item2: S2,
  item3: S3
}

With this feature at every definition using this type I have to use:

function user(map: LiteralMap<*, *, *>) {}

Now if I need to add a new literal to my map I have to update this to:

type LiteralMap<S1 extends string, S2 extends string, S3 extends string, S4 extends string> = {
  item1: S1,
  item2: S2,
  item3: S3,
  item4: S4,
}

which is no big deal, but now I also have to update every single use of this to:

function user(map: LiteralMap<*, *, *, *>) {}

With LiteralMap<**> I can just update the definition without affecting every area it is used.

@svieira svieira mentioned this pull request Sep 1, 2018
4 tasks
@xaviergonz
Copy link

xaviergonz commented Sep 1, 2018

Or it could follow the tuple system

type LiteralMap<S1?, S2?, S3?> = {
  item1: S1,
  item2: S2,
  item3: S3
}

function user(map: LiteralMap) {} // infer, infer, infer
function user(map: LiteralMap<boolean>) {} // boolean, infer, infer
function user(map: LiteralMap<_, boolean>) {} // infer, boolean, infer

type LiteralMap<S1, S2, S3?> = {
  item1: S1,
  item2: S2,
  item3: S3
}

function user(map: LiteralMap) {} // not allowed, S1 and S2 missing
function user(map: LiteralMap<boolean>) {} // not allowed, S2 missing
function user(map: LiteralMap<_, boolean>) {} // infer, boolean, infer

alternatively it could use the default assignation (which I guess makes more sense, since if you want it to infer the default type makes no sense?)

type LiteralMap<S1 = _, S2 = _, S3 = _> = {
  item1: S1,
  item2: S2,
  item3: S3
}

function user(map: LiteralMap) {} // infer, infer, infer
function user(map: LiteralMap<boolean>) {} // boolean, infer, infer
function user(map: LiteralMap<*, boolean>) {} // infer, boolean, infer

type LiteralMap<S1, S2, S3 = _> = {
  item1: S1,
  item2: S2,
  item3: S3
}

function user(map: LiteralMap) {} // not allowed, S1 and S2 missing
function user(map: LiteralMap<boolean>) {} // not allowed, S2 missing
function user(map: LiteralMap<_, boolean>) {} // infer, boolean, infer

@aradalvand
Copy link

I'm relatively new to TypeScript and I expected this feature to already be available.
Is there anything stopping this PR from being merged?

@yume-chan

This comment has been minimized.

@Losses

This comment has been minimized.

@ilyha81
Copy link

ilyha81 commented Feb 9, 2022

Still no progress?
So sad, we need it so much for years.

@cmolina
Copy link

cmolina commented Mar 28, 2022

At mswjs/msw#1175 we are trying to infer path parameters from a URL. We haven't find a way yet to both allow customers to define generics, and infer the parameters.

Is there any workaround that we can use today to get this shipped? Thanks.

@Andarist
Copy link
Contributor

Curried functions (outer one for explicit generics, inner one for inferred ones). Or allow providing generics through "fake" properties/arguments (u can check out what we are doing with schema in XState, link)

@Andarist
Copy link
Contributor

Given the recent addition of variance annotations - would it make sense to introduce infer annotation for type parameters that would spare the consumers using an explicit _ sigil at the call site?

@tannerlinsley
Copy link

Given the recent addition of variance annotations - would it make sense to introduce infer annotation for type parameters that would spare the consumers using an explicit _ sigil at the call site?

I was thinking the exact same thing the other day after seeing both the new generic constraint syntax and variance annotations, I feel like we should be able to come up with something better than _

@Federerer
Copy link

I would expect that this is something that surprises people quite a bit and it's something that is rarely wanted.
I've stumbled upon this today and after a ton of searching ended up here.
In my case I want to use a string literal type:

function foo<T, TName extends string = string>(name: TName): [T, TName] {
  [...]
}

const a = foo('bar'); // correct  a: [ unknown, 'bar' ]
const b = foo<number>('baz'); // not correct b: [ number, string ] instead of [ number, 'baz' ]
const c = foo<number, 'baz'>('baz'); // correct c: [ number, 'baz' ]

And looking at the example, the TName extends string = string is probably not the best way of writing it, because string should never be a valid type here. It should be always a string literal type, so the type should be TName extends string without the default, but then, you will get Expected 2 type arguments, but got 1. error, which is probably better than getting a string default when you don't expect it. 😕

@mdecurtins
Copy link

Rather than using curried functions, which seem like extra gymnastics, I've resorted to "fully qualified" typing; that is, just fixing the "expected 2 type arguments, but got 1" problem that Typescript reports by filling in the type parameter explicitly that should be inferred. Admittedly, mine is a simple case:

interface FooArgs { 
  //...
}

function foo<T extends Builder, U extends Record<string, string|number>>( builder: T, args: FooArgs, key: keyof U ) {
  //...
}

Where T can be inferred, but key depends on U because of keyof.

Still, it would be really, really helpful to be able to write generic functions knowing that in most cases I only need to focus on typing where type information is required to complete the function call. Here's hoping this PR regains some momentum!

@btoo
Copy link

btoo commented Aug 30, 2022

in light of #46827, i'm following up on #26349 (comment) - afaict, a lot (albeit not all) of the feature requests in this proposal are resolved via one of these two mechanisms:

@ChibiBlasphem
Copy link

ChibiBlasphem commented Sep 8, 2022

@btoo

in light of #46827, i'm following up on #26349 (comment) - afaict, a lot (albeit not all) of the feature requests in this proposal are resolved via one of these two mechanisms:

I don’t understand how it is resolving the issue of having parameters infered in a generic typed function. This is literally something so many people want and it breaks nothing. That’s the default behavior when no type is given, we would like to do the same when we need to pass on (without having to respecify every types or having to redefine a contract)

@insidewhy
Copy link

@btoo

in light of #46827, i'm following up on #26349 (comment) - afaict, a lot (albeit not all) of the feature requests in this proposal are resolved via one of these two mechanisms:

I don’t understand how it is resolving the issue of having parameters infered in a generic typed function. This is literally something so many people want and it breaks nothing. That’s the default behavior when no type is given, we would like to do the same when we need to pass on (without having to respecify every types or having to redefine a contract)

It would break the case when latter arguments specify defaults. The inferred type would be chosen (new) over the default type (current). Although I think it's very very unlikely there's many cases in the world where the default value would either be different to the inferred value, or a type that leads to a successful compilation. I think 99.9999% of the time this feature would just turn a compiler error into a desirable type selection.

@ChibiBlasphem
Copy link

@btoo

in light of #46827, i'm following up on #26349 (comment) - afaict, a lot (albeit not all) of the feature requests in this proposal are resolved via one of these two mechanisms:

I don’t understand how it is resolving the issue of having parameters infered in a generic typed function. This is literally something so many people want and it breaks nothing. That’s the default behavior when no type is given, we would like to do the same when we need to pass on (without having to respecify every types or having to redefine a contract)

It would break the case when latter arguments specify defaults. The inferred type would be chosen (new) over the default type (current). Although I think it's very very unlikely there's many cases in the world where the default value would either be different to the inferred value, or a type that leads to a successful compilation. I think 99.9999% of the time this feature would just turn a compiler error into a desirable type selection.

It's not about changing the current behavior but adding a infer of the _ sigil to specify you want your types to be infered from parameters. This, does not break anything

@tannerlinsley
Copy link

tannerlinsley commented Sep 9, 2022 via email

@rolivegab
Copy link

This PR is awesome, but partial/named generics is so much better, as it's follows the same principles from underlying javascript, which in fact everyone here is familiar with.

@sampbarrow
Copy link

Any chance this gets implemented? Would be extremely useful

@Thundercraft5
Copy link

Thundercraft5 commented Dec 13, 2022

Just a small thing, but allowing the _ sigil for partial inference in classes for super calls (#36456, and also thanks to #51865), would allow a whole new pattern for classes and subclasses to be fully workable typewise, like this:

type Options = {
    name: string;
};

class Command<const O extends Options, R extends string> {
    constructor(options: O, executor: R) { /* ... */ }
    
    getName(): O["name"] { /* ... */ }
    
    invoke(): R { /* ... */ }
}

class Subcommand extends Command<
    _, // or whatever would be implemented, `infer`, `auto`, `*`, ect...
    "error" | "success",
> {
    constructor() {
        super({ name: "subcommand" }, () => "success" as const);
        // Different super calls by letting the types be inferred *entirely* would make type resolution extremely difficult...
        /*
          if (Math.random() > 0.5) {
              super({ name: "sub2" }, () => "error");
          } else {
              super({ name: "sub1" }, () => "success");
          }
        */
        // What do we resolve to? Both types? Or the first?
        
        // We now have direct access to the information we passed *once*, keeping with the DRY principle.
        this.getName(); // => "subcommand"
    }
}

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