-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Allow defering type check of default value for generic-typed function parameter until instantiation #58977
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
Comments
Generics aren't C++ templates; there is no template specialization or anything like that. The implementation of a generic has to be valid for all possible types |
Duplicate of #56315 and note that they generally consider two issues duplicates if they both target the same problem, even if they propose different ways to solve the problem. |
I think this is a better write-up than the prior two, so forward-duping. This is the sort of thing that really does need .d.ts parity to be useful, and the problem here is how to represent this in .d.ts files, where default values aren't manifested. Today if you write the function in the first example, the .d.ts emit is declare function x<T extends boolean>(arg1?: T): T; So there's no information that Sometimes the default expression is one that can be safely printed in the That said, I think non-literal default values are quite rare in practice, and we could maybe get away with just allowing it. We've been reluctant to allow default values in declaration file in parameters because it's something that very much can be out of sync with runtime values in a way that's pretty dangerous, but on the other hand it's pretty useful to be able to see that |
See also #16665 |
Jotting down some raw notes from an earlier conversation interface AnimalKind {
cat: { meow: true };
dog: { woof: true }
}
// Why have a defaulted generic arg? Demo:
function getPet<K extends keyof AnimalKind>(kind: K = "dog"): AnimalKind[K] {
return null as any;
}
const c = getPet<"cat">(); // no
// How to reason about this example?
declare const aa: true | undefined;
const j = x(aa);
// ^?
// j: true, T = true
x(undefined); |
Allowing this to get checked at the call site is tricky:
Overall this would likely be a very difficult and invasive PR affecting a pretty broad range of problems - declaration file emit, declaration file parsing, overload selection (!), generic inference, constraint validation, argument validation, and more. It'd be instructive to see a working PR here to evaluate the total trade-off. I think the upsides, especially for #16665, are there, but I don't think something that is several hundred additional lines of code would meet the bar as a feature. If it turns out this can be done simply, though, it'd likely be something we'd take serious consideration of. |
π Search Terms
TS2322, generic-typed function, default parameter
β Viability Checklist
β Suggestion
I've read #49158 but I think my motivating example (and suggested solution) are different enough that it makes sense to open a new issue.
In essence, I think it would be nice to have a way to avoid
TS2322
("Type 'X' is not assignable to type 'Y'. 'Y' could be instantiated with an arbitrary type which could be unrelated to 'X'.") on default function parameters by deferring the check until the call site. In essence: at each caller, the caller is obligated to do one of the following:It would even be reasonable to require that the default value of the parameter would allow the type parameter to be inferred (ie: so that "naive" uses of the call without specifying the type parameter nor the function parameter) would be valid.
Here's a very simple idea of how the feature would work:
Note in particular that it's not possible to use optional parameters to accomplish the above. We need the
x<true>()
case to fail, because the default value is `false, after all.π Motivating Example
Cockpit is an interface for performing admin tasks on Linux servers. We essentially allow the Javascript running in the browser to interact with a set of APIs on the server via "Channels". There's channels for reading files, creating files, connecting to sockets, spawning commands, making D-Bus calls, etc. Channels can be opened in binary or text mode, which is controlled by passing
{ binary: true }
as part of the options object passed when creating a given channel.The various channel subtypes have higher-level APIs which wrap the raw channel implementation. Those in turn are sometimes wrapped by even higher level APIs which pass through the options object. For example,
cockpit.spawn()
will spawn a command, and we have a wrappercockpit.python()
which will pass a given Python script via the-c
argument and capture the result.In most of these "wrapping" cases, the presence/value of the
binary
option on the options object will impact the return type of the function.At first we did something like this:
which produced the correct effect. The options object is mandatory if you want binary, and it must contain
binary: true
.It's very difficult to "wrap" such APIs, though: each wrapper needs to provide its own set of overloaded definitions, and convincing TypeScript that the internal call (to the "next layer") is correct is very difficult.
More recently I've come up with something like this simplified example, which works reasonably OK:
The problem here, though, is that because the
options
array is optional, you can force a different type for the function and omit the options:I've gone through a bunch of different approaches to try to figure out a way to approach this but it all comes down to the fact that an optional parameter of the generic type cannot possibly constrain the instantiated type of the function call by its absence. You can always instantiate with your chosen type and the absent parameter will satisfy it (since it's optional, after all).
This is where the idea with default values comes in. I don't actually want the parameter to be optional: I want to specify its default value, and I want that default value to be checked at the call site to match the instantiated type of the function call.
π» Use Cases
The text was updated successfully, but these errors were encountered: