简体   繁体   English

typescript 可以在没有`as const`的情况下推断字符串文字类型

[英]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 .为了让 js 能够很好地使用 api,如何让编译器在不使用as const的情况下推断"bar"类型而不是string

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:this answer中所述, util 类型可以提供帮助:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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