【问题标题】:Typescript variable with single type form object具有单一类型表单对象的打字稿变量
【发布时间】:2020-04-08 22:19:03
【问题描述】:

考虑以下接口/类型:

interface Ifc {
  fieldA: string;
  fieldB: number;
}

我想要一个可分配给非对象类型变量的类型,告诉 TypeScritp 如下:

嘿 TypeScript,这个类型是接口Ifc中包含的所有类型中的一个单一类型

这给了我以下控制类型的方法:

// [[ ]] means placeholder
let oneFromIfc0: [[Type I can't figure out]] = 'Hey there' // It's ok, string is in Ifc type
let oneFromIfc1: [[Type I can't figure out]] = false // error, boolean does not conform to any field of Ifc

如果是对象,则可以使用映射的可选类型来解决:

type partialType = {
  [k in keyof Ifc]?: Ifc[k];
}

这基本上指示 TypeScritp 执行以下操作:

嘿 TypeScript,取 Ifc 的任何字段名称,使其成为可选的。然后把这个字段类型复制到这个字段中。

但与我需要的相比,它有一些缺陷:

  • 需要使用不具有标量值的对象(使用o.fieldA 而不是fieldA
  • 允许将Ifc 的多个字段映射到新对象
  • 字段名必须与Ifc字段名一致

【问题讨论】:

    标签: typescript


    【解决方案1】:

    如果你想得到一个接口中所有可能值的联合,你可以使用T[keyof T]

    interface Ifc {
      fieldA: string;
      fieldB: number;
    }
    
    let oneFromIfc0: Ifc[keyof Ifc] = 'Hey there' // ok
    let oneFromIfc1: Ifc[keyof Ifc] = false // err
    

    Playground Link

    【讨论】:

    • 很高兴再次见到你,泰坦。好吧,是的,我忽略了这一点的简单性和事实让我觉得有点愚蠢:) 谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 2020-03-22
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    相关资源
    最近更新 更多