【问题标题】:What does -? mean in TypeScript?什么-?在 TypeScript 中是什么意思?
【发布时间】:2019-02-24 07:02:56
【问题描述】:

我在type definitions for prop-types看到了这条线:

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

如果没有-,这将是一个相当标准的部分mapped type,但我在文档中找不到任何地方提到-?

谁能解释-?是什么意思?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    +- 允许控制映射类型修饰符(?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?

    【讨论】:

    • 我有点奇怪,是你回答的(我的书读到一半了)。 :) 这在你的书中或任何地方的 TypeScript 文档中都有介绍吗?
    • 从 typescript link 查看此文档,它提供了有关函数和参数的其他信息的更多见解。
    • @brian-lives-outdoors 遗憾的是还没有github.com/basarat/typescript-book/issues/402
    • @basarat 不用担心 :) 感谢您的快速回答!我很喜欢你的书?
    • 在引入此语法时可能值得注意:github.com/microsoft/TypeScript/commit/… 以及用于符号的名称:MappedTypeModifiers
    猜你喜欢
    • 2020-06-08
    • 2011-08-12
    • 2017-06-11
    • 2018-03-05
    • 2023-03-27
    • 2016-08-17
    • 2010-12-28
    • 2016-11-03
    • 2019-04-02
    相关资源
    最近更新 更多