When working with generics, i came across this issue, which you can find reproduced here.
I wish to understand if that is desired behavior or an abnormality.
...
3 class Foo<P = any> { // <-- No Error
4 static bar<T = any>(quo: T): T { // <-- Errors
5 return quo;
6 }
7 }
...
Error Tab
4: static bar<T = any>(quo: T): T {
^ Unexpected token =
4: static bar<T = any>(quo: T): T {
^ Unexpected reserved type
How do you work around this for now?
AFAIK default values for generics works only for parametrized generics in where only classes, type aliases and interfaces can have parametrized generics. https://flow.org/en/docs/types/generics/#toc-adding-defaults-to-parameterized-generics
@hayk94 That stack answer is not adding a default, it's adding a bound to the generic.
The way this is presented in the documentation is confusing. The distinction between generics and _parameterized_ generics is totally unclear.
Functions and function types do not have parameterized generics.
What does this mean? Functions can have generics:
type Func = <A>(A) => A;
Functions can have bound generics:
type Func = <A: Object>(A) => A;
Functions can take type parameters:
const func: Func = (a) => a;
func<{ a: number }>({a: 1, b: 2});
But they can't take defaults:
type Func = <A=void>(A) => A;
Does this mean generics on functions are somehow less parameterized? Are there other things that generics on functions can't do that other generics can? Should these questions be answered in the docs? Typescript seems to support this.
In my case I'm trying to do something like this:
// I want to be able to call `create` either with or without the first arg, if
// i pass the first arg the return type should be `R`, if I don't, it should be `string`.
type Generator<T> = () => T;
const create = <R=string>( // throws an error as defaults aren't supported
generator: Generator<R> = () => 'test',
): R => generator();
(create(): string);
(create(() => 1): number);
I'm not sure my problem would be solved by defaults, anyway. I think stuff in the default position just doesn't quite work the same. I'm also unclear on why
type Generator<T> = () => T;
const create = <R: string | number>(
generator: () => R, // this works
//generator: Generator<R>, // but this doesn't
): R => (generator || (() => 'test'))();
create(() => 1);
declare class Common<T> {
hook: Hook<T = this>;
pass: Pass<T = this>;
done: Done;
}
@goodmind which issue covers this use case?
``
declare class Common<T = this> { // throws Unexpected use ofthis` type.
I don't think there is one
Most helpful comment
Fixed by https://github.com/facebook/flow/commit/c18ee0d8ee7999ef65ee21d0113b7351c5dc1e15