'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



Solution 1:[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;

Solution 2:[2]

You can use django forms instance for saving any predefined value without showing or render those fields to your users or html template. Here is an example how to automatically save your username and created_date fields .

if fm.is_valid():               
                fm = fm.save(commit=False)
                fm.instance.username = request.user  
                fm.instance.created_date = timezone.now()
                fm.save()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 V. Yao
Solution 2 Willem Van Onsem