Home > Net >  TypeScript: autocomplete but disable inferring
TypeScript: autocomplete but disable inferring

Time:08-30

Suppose we have a type:

type A = {
  a1?: string;
  a2?: number;
  a3?: boolean;
}

And a variable with this type for autocompletion:

const b: A = {
  a1: "test";
}

b now has type A, but I want to infer this type:

type B = {
  a1: string;
}

Is it possible?


I need to create function with signature like this:

type A = {
  a1?: string;
  a2?: number;
  a3?: boolean;
}

const b = build<A>(() => {
  return {
    // autocompletion from type A should works
    a1: string;
  }
});

where type of b should be:

type B = {
  a1: string;
}

CodePudding user response:

With satisfies operator merged into TS 4.9, the straightforward approach with TS 4.9 (slated for November 2022) is:

type A = {
  a1?: string;
  a2?: number;
  a3?: boolean;
}

const b = {
  a1: "test"
} satisfies A;

See:

CodePudding user response:

When I understood your question right, you want to to this

Playground Exmaple:

type A = {
  a1?: string;
  a2?: number;
  a3?: boolean;
}

const b: A = {
  a1: "test"
}

function identityCheck<T = never>() {
  return <I>(input: I & T) => input as I;
}

const b1 = identityCheck<A>()({
  a1: "test"
})

// now only a1 is shown in auto-complete
b1.a1

see also: Is there a way to use a typescript interface with optional keys, but then concretize that the keys are there?

CodePudding user response:

Based on TmTron answer I created a class based solution cuz I don't like how currying looks:

class SomeBuilder<S = never> {
  constructor() {}

  build<T>(callback: () => S & T) {
    return callback as () => T;
  }
}

  • Related