50

I have the following function:

async function get<U>(url: string): Promise<U> {
    return getUrl<u>(url);
}

However, it is possible to call it like this (U is set to any by TS):

get('/user-url');

Is there a way to define this function such that it requires U to be provided explicitly, as in

get<User>('/user-url');
3
  • What is your TypeScript definition of getUrl? And what are you going to achieve by adding that requirement?
    – jaboja
    Commented Jul 4, 2018 at 12:04
  • @jaboja I think the use case is pretty clear, I have seen numerous questions here on SO as to why is get (of whatever API) returning {} or any and not what I expect it to, or how do I tell get what type my API returns. Always the get has a type parameter that people do not see at first. With such a restriction it becomes mandatory and obvious Commented Jul 4, 2018 at 12:07
  • 1
    What problem are you trying to solve? After all, U would default to {}, and you'd get an error when you try to access any properties on it, which would alert you to the problem. Commented Jul 4, 2018 at 12:28

7 Answers 7

39

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<U = void>(url: string & (U extends void ? "You must provide a type parameter" : string)): Promise<U> {
    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>('/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

3
  • 3
    doing so will not allow you to actually use extends to set up generic type constraint
    – SET001
    Commented Jan 18, 2020 at 15:08
  • 1
    Thanks for the link to your other answer. get('/user-url') won't typecheck but const n: number = await get('/user-url'); will. You need the NoInfer boxing trick from your that other answer to work around that.
    – Coderer
    Commented Jul 6, 2021 at 12:24
  • What is the purpose of string & ?? Deleting it seems to work the same
    – boludo kid
    Commented Aug 29 at 15:29
12

You could use multiple type parameters:

function contractType<T = void, U extends T = T>(value: unknown): U {
    return value as U
}

const example1: string = contractType(17) // error
const example2: string = contractType("value") // error
const example3: string = contractType<string>("value") // ok

https://github.com/Microsoft/TypeScript/issues/14829#issuecomment-288902999

8
function createCommand<P extends WhatEver = never>(a: P): P {
    a.whatEverProperty; // a is always instanceof WhatEver. Never is overlooked here.
}

The easiest solution for most of cases is specifying never as default type argument value. never is always assignable to the type argument, even if you extend it with WhatEver, so the body of function is not affected, but the return value here will be never affecting the consumers ability to use this function in any meaningful way.

(Consumers/callers will get an error at the point they try to use the return value, but if your function is called purely for side-effects, you may want to consider the approach outlined in @Titian's answer)

You can use conditional types to make the return type never when you normally wouldn't return P:

function createCommand<P extends WhatEver = never>(a: P): P['whatEverProperty'] {
    // a is always instanceof WhatEver. Never is overlooked here.
    return a.whatEverProperty as P extends WhatEver ?
      ? WhatEver
      : never
}
1
  • 2
    This does not address the problem of contextual inference. const s: string = get("./abc") will infer the generic type U = string. The actual problem is that the user is not using the generic parameter to type a function argument. They should actually be returning unknown and explicitly type-checking at runtime, or casting.
    – Coderer
    Commented Jul 6, 2021 at 12:09
2

The other answers here provide some decent workarounds to get your code to work the way you want but none of them address the fundamental problem, which is that you're trying to do unsafe casts to make the typechecker happy.

I don't have the source of your getUrl<T> function but I strongly suspect that it looks a lot like

function getUrl<T>(url: string): Promise<T> {
  return fetch(url).then(resp => resp.json());
}

In this scenario, Response#json() returns Promise<any> which you're quietly casting to Promise<T> -- which is unsafe. When you write const user: User = await get("./user");, the typechecker is happy to infer that you want a Promise<User> back and fills it in for you. It does this even if you provide a default value.

A safer way to do this would be to have getUrl return unknown. This will force you to either check your return value at runtime with a type guard, or at least explicitly cast it ((await get("./user")) as User etc), in which case your linter can chastise you for unsafe casts.

0

Yet another approach! Require a parameter that is used just for the type inference:

/**
 * getFoo gives you a well-typed Foo component
 * ```tsx
 * const foo = getFoo(config)
 * ```
 */
const getFoo = <Keys extends string>(
  _config: Record<Keys, unknown>
) => {
  return FooUntyped as FooType<Keys>
}

If you have objects readily available to pass in for this type inference, and your functions wouldn't otherwise accept a parameter, this may be a good approach for you *as of TS v4.1.2

If you don't have some config object readily available, calling it is a little bit "wtf" but you get an error directly where you call it, instead of somewhere further on:

const foo = getFoo({} as Record<'my' | 'keys', unknown>)

This design/approach happened to actually fix a little kink in my design in another location. I actually added an extra param too my getFoo called defaultProps which are some default props for a given Foo component (Foo is a Form Field component, and config keys are valid field names)

1
  • A bit of a tangent, but this is one circumstance where 1 hook returning 1 component actually seems like a fair pattern. (A hook returning multiple components, however, gets in the way of tree-shaking) Commented Dec 30, 2020 at 4:34
0

I stumbled on your question because of the following Ramda pathOr type definition:

export function pathOr<T>(defaultValue: T, path: Path, obj: any): T;

The function can find a value deep inside an object, following a path.

The problem is that if you don't provide the generic type parameter T, Typescript will use the type from the defaultValue. This makes no sense when the object's content doesn't have the same type at that path.

The solution is complex and only works because there are two arguments. I don't think there's an easy answer to your question that works for all cases.

import {toPath} from 'lodash-es'
import {pathOr} from 'ramda'

// Aternative to lodash `get` where you have to provide a default value and a return type that includes the default value.
// Useful to avoid cases where the return type is inferred from the default value's type but does not fit with the object's content at the path.
export const getOr = <T = never, D extends T = T>(object: unknown, pathStr: string, defaultValue: D): T =>
  pathOr(defaultValue, toPath(pathStr), object)

To be fair, ramda's path function and lodash's get function both try really hard to find the correct return type based on the object and the path, but I don't see how using a T type for both the default value and return value could be a good idea.

0

As long as you always use the return value, you can add two overrides to your example:

declare function getUrl<U> (url: string): U
type U = Record<string, unknown>

function get<U extends undefined | string> (_: U): void
async function get<U extends object> (url: string): Promise<U>
async function get<U extends object> (url: string): Promise<U> {
  return getUrl<U>(url)
}

get('/user-url') // No error, unfortunately
await get('/user-url') // Error
const promise = get('/user-url') // Error

await get<U>('https://...') // Okay

Note that this makes the return type void if <U> isn't provided, so although you'll get a TypeScript error if you try to use the return value, you can still call it and ignore the return type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.