在TypeScript中引用推断类型

Sea*_*ess 5 javascript closures dependency-injection inferred-type typescript

有没有办法在TypeScript中引用推断类型?

在下面的例子中,我们得到了很好的推断类型.

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

var test = Test()
test.hello // works
test.bob   // 'bob' doesn't exist on inferred type
Run Code Online (Sandbox Code Playgroud)

但是,如果我想定义一个带有类型参数的函数:"Whatever Test返回",而不显式定义接口,该怎么办?

function Thing(test:???) {
  test.hello // works
  test.bob   // I want this to fail
}
Run Code Online (Sandbox Code Playgroud)

这是一种解决方法,但如果Test具有自己的参数,它会变得毛茸茸.

function Thing(test = Test()) {} // thanks default parameter!
Run Code Online (Sandbox Code Playgroud)

有没有办法引用Test返回的推断类型?所以我可以输入"Whatever Test return",而无需创建界面?

我关心的原因是因为我通常使用闭包/模块模式而不是类.Typescript已经允许你输入一些类作为类,即使你可以创建一个描述该类的接口.我想输入一些函数返回而不是类.有关原因的更多信息,请参阅Typescript中的闭包(依赖注入).

解决这个问题的最佳方法是,TypeScript添加了定义模块的能力,这些模块将其依赖项作为参数,或者在闭包内定义模块.然后我可以使用spiffy export语法.有人知道这有什么计划吗?

And*_*nti 6

现在可以了:

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

function Thing(test: ReturnType<typeof Test>) {
  test.hello // works
  test.bob   // fails
}
Run Code Online (Sandbox Code Playgroud)

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


Mar*_*rot 0

您可以使用接口的主体作为类型文字:

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

相当于

interface ITest {
    hello: string;
}

function Thing(test: ITest) {
    test.hello // works
    test.bob   // I want this to fail
}
Run Code Online (Sandbox Code Playgroud)

只是不要忘记;每个成员末尾的 。


没有用于命名或引用推断类型的语法。您可以获得的最接近的结果是对要使用的成员使用接口或类型文字。接口和类型文字将匹配至少具有已定义成员的任何类型。“鸭子打字”