Search code examples
typescriptintersectiontypescript-types

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". How do I achieve the intellisense, by that I mean, instead of showing the "Partial & Test2" it shows

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

which would be the actual result of the TestResult

Thank you in advance


Solution

  • 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)

    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.