6

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

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

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

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

但是,如果我想定义一个接受类型参数的函数:“无论Test返回什么”,而不显式定义接口,该怎么办?

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

这是一种解决方法,但如果 Test 有自己的参数,它会变得很麻烦。

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

有什么方法可以引用任何 Test 返回的推断类型?所以我可以在不创建界面的情况下输入“Whatever Test returns”之类的内容?

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

解决这个问题的最佳方法是,如果 TypeScript 添加了定义将其依赖项作为参数的模块的能力,或者在闭包内定义模块。然后我可以使用漂亮的export语法。有谁知道有没有这方面的计划?

4

2 回答 2

3

现在可以:

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-in​​ference-in-conditional-types

于 2019-12-21T20:43:34.133 回答
0

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

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

相当于

interface ITest {
    hello: string;
}

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

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


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

于 2012-12-07T19:31:21.103 回答