2

In order for js to use the api well, how to make the compiler infer "bar" type instead of string without using as const.

declare function define<T>(
  options: {
    foo: string;
    bar: T;
  }
): void;

declare function create<T>( cmd: T ): T;

define( {
  foo: "foo",
  bar: create( "bar" ) // It still string, instead of "bar"
} );

playground

  • 2
    Is `T` always going to be a subtype of `string`? If so you can do [this](https://tsplay.dev/WoDl8w). If not then what possible types will it be? – jcalz Jan 24 '22 at 21:45

1 Answers1

1

As mentioned in this answer, a util type can help:

type StringLiteral<T> = T extends string ? string extends T ? never : T : never;

declare function define<T>(
  options: {
    foo: string;
    bar: StringLiteral<T>;
  }
): void;
V. Yao
  • 26
  • 3