kan TypeScript het stringliteraletype afleiden zonder `as const`
Om ervoor te zorgen dat js de api goed kan gebruiken, hoe kan de compiler het type "bar" afleiden in plaats van string zonder as const te gebruiken.
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"
} );
speelplaats
Antwoord #1
Zoals vermeld in dit antwoord, kan een util-type helpen:
type StringLiteral<T> = T extends string ? string extends T ? never : T : never;
declare function define<T>(
options: {
foo: string;
bar: StringLiteral<T>;
}
): void;
