TypeScript中的-?代表什么意思?

67

我在prop-types的类型定义中发现了这行代码:

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

没有 -,它就是一个相当标准的部分映射类型,但我找不到文档中任何介绍 -? 的地方。
有人能解释一下 -? 是什么意思吗?

更新的文档:https://www.typescriptlang.org/docs/handbook/2/mapped-types.html#mapping-modifiers - Experimenter
2个回答

113

+- 可以控制映射类型修饰符 (?readonly)。 -? 表示必须全部存在,即它移除了可选性 (?),例如:

type T = {
    a: string
    b?: string
}


// Note b is optional
const sameAsT: { [K in keyof T]: string } = {
    a: 'asdf', // a is required
}

// Note a became optional
const canBeNotPresent: { [K in keyof T]?: string } = {
}

// Note b became required
const mustBePreset: { [K in keyof T]-?: string } = {
    a: 'asdf', 
    b: 'asdf'  // b became required 
}

更多

我在这里讲解了这些映射类型修饰符:https://www.youtube.com/watch?v=0zgWo_gnzVI


2
我有点兴奋,因为回答我的是你(我正在读你的书)。 :) 这个问题在你的书或TypeScript文档中有涉及吗? - Brian Adams
请查看 TypeScript 的这份文档 链接,它提供了有关函数和参数的其他信息。 - Pramod Patil
@brian-lives-outdoors 很遗憾目前还没有。https://github.com/basarat/typescript-book/issues/402 - basarat
@basarat 不用担心 :) 感谢你在这里的快速回答!我很喜欢你的书。 - Brian Adams
2
也许值得注意的是,此语法引入的时间:https://github.com/microsoft/TypeScript/commit/a629acd8fd4844742fdd01ab6cf55afa9377db0e以及用于符号的名称:MappedTypeModifiers - Beau
2
啊?+? 是干嘛用的?它和仅仅使用 ? 是等价的吗?——编辑:答案是肯定的(https://www.typescriptlang.org/docs/handbook/release-notes/overview.html#improved-control-over-mapped-type-modifiers) - Simon Farshid

0

-?解释为去除可选性,这将使其变为必填项。此处是当前的官方文档。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接