Skip to content

Strange behaviour with 'void' as function argument #31645

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

Closed
lifaon74 opened this issue May 29, 2019 · 3 comments
Closed

Strange behaviour with 'void' as function argument #31645

lifaon74 opened this issue May 29, 2019 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@lifaon74
Copy link

TypeScript Version: 3.4.5, 3.5.0-rc and next

Search Terms:
void, function, argument, template

Code

class A<T> {
  constructor(a: T) {
  }
}

class B {
  constructor(a: void) {
  }
}


const a = new A<void>(); // error ! => variable 'a' should be optional !
const b = new B();

Expected behavior:
It's pretty hard to understand why with a template function having a 'void' type (in class A), the behaviour is not the same as the class B.
Allowing a developper to put 'void' as template and providing 0 argument is sometimes required.

The following 'solution' is not acceptable, because the variable a would always be optional where I want to have it optional only if T is void.

class A<T> {
  constructor(a?: T) {
  }
}

Actual behavior:
class A diverge from B even if the typing is conceptualy the same.

Playground Link:
https://www.typescriptlang.org/play/#src=class%20A%3CT%3E%20%7B%0D%0A%20%20constructor(a%3A%20T)%20%7B%0D%0A%20%20%7D%0D%0A%7D%0D%0A%0D%0Aclass%20B%20%7B%0D%0A%20%20constructor(a%3A%20void)%20%7B%0D%0A%20%20%7D%0D%0A%7D%0D%0A%0D%0A%0D%0Aconst%20a%20%3D%20new%20A%3Cvoid%3E()%3B%20%2F%2F%20error%20!%0D%0Aconst%20b%20%3D%20new%20B()%3B

More examples:

type CType<T> = T extends any[] ? T : void;

class C<T> {
  constructor(a: CType<T>) {
  }
}

const c = new C<number>(); // error !
function foo<T>(a: T): void {
}

foo<void>(); // error !
@jack-williams
Copy link
Collaborator

Duplicate of #29131.

The short answer is that arity checking that accounts for void is done before generic instantiation.

@nmain
Copy link

nmain commented May 29, 2019

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label May 29, 2019
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

5 participants