TypeScript Reference

Is there a way to refer to an inferred type in TypeScript?

In the following example, we get good deduced 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 accepts a parameter like: "Whatever Test is returned," without explicitly defining an 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 its own parameters.

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

Is there any way to refer to the inferred type of any test result? So I can print something like β€œWhatever test is returned,” without creating an interface?

The reason for me is that I usually use a closure / module pattern instead of classes. Typescript already allows you to enter something as a class, even if you can create an interface that describes this class. I want to print something as a function returned by a function instead of a class. See Closing in Typescript (Injection Dependency) for more information on the causes.

The BEST way to solve this problem is if Typescript has added an abstraction to define modules that accept their dependencies as parameters, or to define a module inside a closure. Then I could just use spiffy export syntax. Does anyone know if there are any plans for this?

+4
source share
1 answer

You can use the body of the interface as a literal like:

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

equivalently

 interface ITest { hello: string; } function Thing(test: ITest) { test.hello // works test.bob // I want this to fail } 

Just do not forget ; at the end of each element.


There is no syntax for naming or referencing derived types. The closest you can get is the use of interfaces or generic literals for the members you intend to use. Interfaces and type literals will match any type that at least has specific members. "Duck-typing"

+1
source

All Articles