kan typescript udlede string literal-typen uden `as const`
For at js kan bruge API'en godt, hvordan får man compileren til at inferere "bar"-typen i stedet for string uden at bruge 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"
} );
legeplads
Svar #1
Som nævnt i dette svar, kan en util-type hjælpe:
type StringLiteral<T> = T extends string ? string extends T ? never : T : never;
declare function define<T>(
options: {
foo: string;
bar: StringLiteral<T>;
}
): void;
