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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With