简体   繁体   中英

can typescript infer the string literal type without `as const`

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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