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

OptionalPropNames<T>: unexpected result in conditional type #21989

Closed
yortus opened this issue Feb 16, 2018 · 1 comment
Closed

OptionalPropNames<T>: unexpected result in conditional type #21989

yortus opened this issue Feb 16, 2018 · 1 comment

Comments

@yortus
Copy link
Contributor

yortus commented Feb 16, 2018

TypeScript Version: 2.8.0-dev.20180216

Code

// Type-level filters to extract just the required or optional properties of a type
// Defns from https://github.com/Microsoft/TypeScript/pull/21919#issuecomment-365491689
type OptionalPropNames<T> = { [P in keyof T]: undefined extends T[P] ? P : never }[keyof T];
type RequiredPropNames<T> = { [P in keyof T]: undefined extends T[P] ? never : P }[keyof T];
type OptionalProps<T> = { [P in OptionalPropNames<T>]: T[P] };
type RequiredProps<T> = { [P in RequiredPropNames<T>]: T[P] };

// Let's extract just the optional property names in a type
type PropNames = OptionalPropNames<{req: string, opt?: number}>;   // Names = "opt" | undefined

Expected behavior:
PropNames = "opt"

Actual behavior:
PropNames = "opt" | undefined. How did that undefined get in there?

Related Issues:
Noticed this while writing up #21988, but wasn't sure if the cause was related or not.

The RequiredProps and OptionalProps definitions come from #21919 (comment)

@yortus
Copy link
Contributor Author

yortus commented Feb 20, 2018

I worked it out. This is a result of the way mapped types carry over modifiers (readonly, ?) from the source type to the mapped type. This can be addressed using the new -? syntax added in #21919:

type OptionalPropNames<T> = { [P in keyof T]-?: undefined extends T[P] ? P : never }[keyof T];
                                    //      ^^ new syntax to remove optional modifiers
type PropNames = OptionalPropNames<{req: string, opt?: number}>;   // PropNames = "opt" ✓✓

@yortus yortus closed this as completed Feb 20, 2018
@microsoft microsoft locked and limited conversation to collaborators Jul 3, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant