Home:ALL Converter>Reference an inferred type in TypeScript

Reference an inferred type in TypeScript

Ask Time:2012-12-08T03:22:00         Author:Sean Clark Hess

Json Formatter

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?

Author:Sean Clark Hess,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/13769659/reference-an-inferred-type-in-typescript
André Willik Valenti :

It's now possible:\n\nfunction Test() {\n return { hello: \"world\" }\n}\n\nfunction Thing(test: ReturnType<typeof Test>) {\n test.hello // works\n test.bob // fails\n}\n\n\nhttps://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types",
2019-12-21T20:43:34
yy