TransWikia.com

Use type that isn't exported

Stack Overflow Asked on November 4, 2021

library is a Typescript module. It exports a function someFunction that is made for a very specific purpose. It is called with a string, and that string must be one of several values.

In library, someFunction has been defined with an interface that asserts that its parameter is one of several strings – "value1" | "value2" | .... This interface is not exported.

Consider the following end-user code, which wraps someFunction in another:

import { someFunction } from "library"

function doThing(text: string): void {
  someFunction({
    content: text,
  })
}

Typescript throws an error – rightfully so – that type 'string' is not assignable to type '"value1" | "value2" | ....

The best solution here would be to change the type of doThing‘s argument to the same type that someFunction expects. However, the type is very long, and not guaranteed to be the same between versions. I’d like to import it – but it’s defined as a property on an interface, and that interface isn’t exported.

Without changing the type of text to any, how can I correctly type text?

One Answer

You can use conditional types with typeof and lookup types.

Solution to your Example

// Assume
function someFunction(arg: { content: 'value1' | 'value2' }) { };


// How to get type of content `value1|value2`
type Content = Parameters<typeof someFunction>[0]['content']; 

Additional Resources

I also have lessons on conditional types and lookup types.

Answered by basarat on November 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP