TypeScript require generic parameter to be provided

前端 未结 4 1111
长发绾君心
长发绾君心 2021-01-07 20:54

I have the following function:

async function get(url: string): Promise {
    return getUrl(url);
}

However, i

4条回答
  •  情话喂你
    2021-01-07 21:07

    There is no built-in support for this, we can however engineer a scenario where not passing in a type parameter will generate an error, using default generic type arguments and conditional types. Namely we will give U a default value of void. If the default value is the actual value of U, then we will type the parameter to the function as something that should not really be passed in so as to get an error:

    async function get(url: string & (U extends void ? "You must provide a type parameter" : string)): Promise {
        return null as any;
    }
    
    get('/user-url'); // Error Argument of type '"/user-url"' is not assignable to parameter of type '"You must provide a type parameter"'.
    
    class User {}
    get('/user-url');
    

    The error message is not ideal, but I think it will get the message across.

    Edit: For a solution where the type parameter is used in parameter types see here

提交回复
热议问题