繁体   English   中英

在 TypeScript 中引用推断类型

[英]Reference an inferred type in TypeScript

有什么方法可以在 TypeScript 中引用推断类型吗?

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

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

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

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

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

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

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

有什么方法可以引用任何 Test 返回的推断类型吗? 所以我可以在不创建界面的情况下键入“无论测试返回什么”的内容?

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

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

现在可以:

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

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

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
}

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


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM