简体   繁体   中英

What does the “-?” syntax mean in TypeScript mapped types?

Can anybody please explain what that "-?" in the following TypeScript type declarations means, compared to just using a "?" there?

type ValidationMap<T> = { [K in keyof T]-?: Validator<T[K]> }

It's not a wildcard. The -? notation was added in TypeScript 2.8 as a way of removing the optional modifier from mapped types.

Basically, it means that ValidationMap<T> has the same keys as T , but none of the properties of ValidationMap<T> is optional, even if the corresponding property of T is. For example:

type Example = ValidationMap<{a: string, b?: number | undefined}>;
// type Example = {a: Validator<string>, b: Validator<number | undefined>}

Here, Example has a required b property even though the type it's mapped from has an optional b property.

(Note that if you change -? to just ? or to +? , it becomes the opposite... you would be adding the optional modifier. The ? notation was added in TypeScript 2.1 as part of the mapped types feature, while the +? notation was introduced in TypeScript 2.8 along with -? .)

Hope that helps. Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM