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

Optional parameter makes the compiler resolve types prematurely for declaration #46724

Open
devanshj opened this issue Nov 8, 2021 · 1 comment
Labels
Bug A bug in TypeScript
Milestone

Comments

@devanshj
Copy link

devanshj commented Nov 8, 2021

Bug Report

πŸ”Ž Search Terms

optional parameter, resolution of types, declaration, optimization

πŸ•— Version & Regression Information

v4.4.4

⏯ Playground Link

Playground for test1.ts Playground for test2.ts

πŸ’» Code

// @file test1.ts
export interface Types {}
  
type Key = 
  Types extends { key: unknown[] }
    ? Types["key"]
    : unknown[]

export const clear = (key: [...Key]) => {}
// @file test2.ts
export interface Types {}
  
type Key = 
  Types extends { key: unknown[] }
    ? Types["key"]
    : unknown[]

export const clear = (key?: [...Key]) => {} // change here, key is optional

πŸ™ Actual behavior

// @file test1.d.ts
export interface Types {
}
declare type Key = Types extends {
    key: unknown[];
} ? Types["key"] : unknown[];
export declare const clear: (key: [...Key]) => void;
export {};
// @file test2.d.ts
export interface Types {
}
export declare const clear: (key?: unknown[] | undefined) => void;

Compiler prematurely resolves Key to unknown[] in test2

πŸ™‚ Expected behavior

Compiler should emit declaration of test2 same as test1 (except the "?" part of course), it should not prematurely resolve Key to unknown[] because one could add a key property to Types via module augmentation which makes the Key type no longer unknown[]

@tadhgmister
Copy link

adding |undefined to the optional parameter fixes this. I suspect the adding of | undefined is to support legacy stuff and it resolves early, if you explicitly say the optional parameter can be passed as undefined then it doesn't need to try to resolve your type to see if adding it would be redundant.

@andrewbranch andrewbranch added the Bug A bug in TypeScript label Nov 9, 2021
@andrewbranch andrewbranch added this to the Backlog milestone Nov 9, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Bug A bug in TypeScript
Projects
None yet
Development

No branches or pull requests

3 participants