1

A lib I'm using exports a function with generic types, but not the type itself, something like this,

// some-lib/index.d.ts
export function libFunction<T>(): InternalLibType<T>;

I'd like to declare a variable of type

const foo: InternalLibType<"something">;

I'm trying to construct the desired type for foo using ReturnType<typeof libFunction> as a starting point, but don't really know how to continue from here.

How can I create a concrete type from the generic type? To be clear, the lib does not export InternalLibType.

The library in question is use-debounce. While it does technically export the type from one of its files, the exported type is not in a file declared in the exports field, thus causing errors with some tools that respect the exports field.

1 Answer 1

2

This line export function libFunction<T>(): InternalLibType<T>; means that libFunction expects explicit generic during the call (which is, AFAIK, unsafe in most cases).

This is not a constructor type which expects a generic argument. It means that you are not allowed to use ReturnType<typeof libFunction<'something'>>.

If you want to infer return type of this function, you have two options:

First, call this function:

const result = libFunction<'something'>();

type Foo = typeof result;

Second, just use InternalLibType<"something">.

SInce TS has a structural type system, type Foo is equal to InternalLibType<"something">

Sign up to request clarification or add additional context in comments.

10 Comments

The second options would be ideal, unfortunately, InternalLibType is not exported
Could you please provide me with a link to third party library? SOme times it is possible to obtain this type from the other one
Added more details in the original post to provide more context than I can with a comment.
@aryzing could you please provide me with exact name of the type or function you want to use
Seems to be that you should create a PR and export this type. I don' see how it can be used without calling the function.
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.