Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference an inferred type in TypeScript

Is there any way to reference an inferred type in TypeScript?

In the following example we get nice inferred types.

function Test() {
    return {hello:"world"}
}

var test = Test()
test.hello // works
test.bob   // 'bob' doesn't exist on inferred type

But what if I want to define a function that takes a parameter of the type: "Whatever Test returns", without explicitly defining the interface?

function Thing(test:???) {
  test.hello // works
  test.bob   // I want this to fail
}

This is a workaround, but it gets hairy if Test has parameters of its own.

function Thing(test = Test()) {} // thanks default parameter!

Is there some way to reference the inferred type of whatever Test returns? So I can type something as "Whatever Test returns", without making an interface?

The reason I care is because I usually use a closure/module pattern instead of classes. Typescript already lets you type something as a class, even though you can make an interface that describes that class. I want to type something as whatever a function returns instead of a class. See Closures in Typescript (Dependency Injection) for more information on why.

The BEST way to solve this is if TypeScript added the abilty to define modules that take their dependencies as parameters, or to define a module inside a closure. Then I could just use the spiffy export syntax. Anyone know if there are any plans for this?

like image 804
Sean Clark Hess Avatar asked Dec 07 '12 19:12

Sean Clark Hess


1 Answers

It's now possible:

function Test() {
    return { hello: "world" }
}

function Thing(test: ReturnType<typeof Test>) {
  test.hello // works
  test.bob   // fails
}

https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types

like image 198
André Willik Valenti Avatar answered Oct 16 '22 14:10

André Willik Valenti