【问题标题】:Intersection Type with inference on Typescript基于 Typescript 推断的交叉点类型
【发布时间】:2020-01-03 00:50:11
【问题描述】:

我有这个代码。

interface Test {
  field1: string;
  field2: string;
}
interface Test2 {
  field3: string;
}

type TestResult = Partial<Test> & Test2;

const a = ():TestResult => {
  return {};
}

这很正常,我的意思是,如果我在 obj 中没有 field3,它不会让我编译,但我没有得到 TestResult 上所有字段的推断,只有“部分和测试2”。 我的意思是,我如何实现智能感知,而不是显示它显示的“Partial & Test2”

field1: string;
field2: string;
field3: string;

这将是 TestResult 的实际结果

提前谢谢你

【问题讨论】:

    标签: typescript intersection typescript-types


    【解决方案1】:

    无法保证类型别名会在工具提示中展开。然而,有一个适用于多个版本的技巧:

    interface Test {
      field1: string;
      field2: string;
    }
    interface Test2 {
      field3: string;
    }
    
    type Id<T> = {} & { [P in keyof T]: T[P] }
    type TestResult = Id<Partial<Test> & Test2>;
    
    const a = ():TestResult => {
      return {};
    }
    

    Id 类型将强制 typescript 扩展类型别名,并为您提供所需的工具提示(尽管对于大型类型,这实际上会适得其反并使工具提示更难阅读)

    type TestResult = {
        field1?: string | undefined;
        field2?: string | undefined;
        field3: string;
    }
    

    你也可以实现相反的,即维护名称而不是使用接口扩展类型:

    interface Test {
      field1: string;
      field2: string;
    }
    interface Test2 {
      field3: string;
    }
    
    type Id<T> = {} & { [P in keyof T]: T[P] }
    interface TestResult extends Id<Partial<Test> & Test2> {}
    
    const a = ():TestResult => {
      return {};
    }
    

    这对于希望有一个稳定名称而不是让 ts 随意扩展类型的大型类型别名非常有用。

    【讨论】:

    • 您好 Titian,感谢您的回答,它就像一个魅力,也感谢您的扩展解释!
    猜你喜欢
    • 2021-02-13
    • 1970-01-01
    • 2021-11-14
    • 2021-10-18
    • 1970-01-01
    • 2018-08-28
    • 2018-07-03
    • 2019-09-17
    • 1970-01-01
    相关资源
    最近更新 更多