简体   繁体   English

在 Typescript 上推断的交集类型

[英]Intersection Type with inference on Typescript

I have this code.我有这个代码。

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

type TestResult = Partial<Test> & Test2;

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

This works normal, by that I mean, It won't let me compile if I don't have the field3 inside of the obj, but I don't get the inference of all of the field on TestResult, only the "Partial & Test2".这工作正常,我的意思是,如果我在 obj 中没有 field3,它不会让我编译,但我没有得到 TestResult 上所有字段的推断,只有“部分 &测试 2”。 How do I achieve the intellisense, by that I mean, instead of showing the "Partial & Test2" it shows我的意思是,我如何实现智能感知,而不是显示它显示的“Partial & Test2”

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

which would be the actual result of the TestResult这将是 TestResult 的实际结果

Thank you in advance先感谢您

There is no way guarantee that a type alias will be expanded in tooltips.无法保证在工具提示中扩展类型别名。 There is however a trick that has worked for several version:然而,有一个技巧适用于多个版本:

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 {};
}

The Id type will force typescript to expand the type alias and will give you the tooltip you desire (although for large types this will actually backfire and make the tooltips harder to read) Id类型将强制打字稿扩展类型别名,并为您提供所需的工具提示(尽管对于大型类型,这实际上会适得其反并使工具提示更难阅读)

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

You can also achieve the inverse, that is maintain the name instead of expanding the type by using an interface:您还可以实现相反的目的,即通过使用接口来维护名称而不是扩展类型:

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 {};
}

This is very useful for large type aliases where you want to have a stable name instead of letting ts expand the types as it wishes.这对于大型类型别名非常有用,您希望拥有一个稳定的名称,而不是让 ts 随心所欲地扩展类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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