对 Typescript 进行推断的交集类型

Intersection Type with inference on Typescript

我有这个代码。

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

type TestResult = Partial<Test> & Test2;

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

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

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

这将是 TestResult

的实际结果

提前致谢

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

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 扩展类型的大型别名非常有用。