简体   繁体   English

TS:跨多个接口的类型推断和 function 签名不推断?

[英]TS: Type inference across multiple interfaces and function signature not inferring?

type TypeOfSomething = "something" | "other thing";

interface HigherLevel<T extends TypeOfSomething> {
  subsection: MidLevel<T>;
}
interface MidLevel<T extends TypeOfSomething> {
  callback: (arg: T) => void;
}

const t = { subsection: { callback: (arg: "something") => {} } } as HigherLevel;

This throws an error (typescript error) Generic type 'HigherLevel' requires 1 type argument(s).ts(2314)这会引发错误(打字稿错误)通用类型“HigherLevel”需要 1 个类型参数(s).ts(2314)

Full Error: Generic type 'HigherLevel' requires 1 type argument(s).ts(2314) On the line with as HigherLevel完整错误:通用类型“HigherLevel”需要 1 个类型参数(s).ts(2314)与as HigherLevel

Why is this?为什么是这样? I have specified the type of arg in the callback function so shouldn't typescript be able to infer the type parameter to HigherLevel ?我已经在回调 function 中指定了arg的类型,所以 typescript 不应该能够将类型参数推断为HigherLevel吗?

I am using as clause, I get a similar error when using it to type the constant t:我正在使用 as 子句,在使用它键入常量 t 时出现类似的错误:

const t: HigherLevel = { subsection: { callback: (arg: "something") => {} } };

It gives me the same error它给了我同样的错误

It would be nice for me to be able to have my types inferred, especially since I am only asking this question as it affects much more complicated typing I am trying to pull off.能够推断出我的类型对我来说很好,特别是因为我只是问这个问题,因为它会影响我试图完成的更复杂的打字。

I don't know if this is a feature of typescript, but it should be in my opinion or I might be thinking of this problem the wrong way.我不知道这是否是 typescript 的特性,但在我看来应该是这样,否则我可能会以错误的方式思考这个问题。

Here is a simpler example without the HigherLevel interface, which might be easier to solve.这是一个没有HigherLevel接口的更简单的例子,可能更容易解决。 I am looking for a solution to the larger problem above still, but this still confuses me:我仍在寻找解决上述更大问题的方法,但这仍然让我感到困惑:

type TypeOfSomething = "something" | "other thing";

interface MidLevel<T extends TypeOfSomething> {
  callback: (arg: T) => void;
}

const t: MidLevel = { callback: (arg: "something") => {} };

Same error, same line:(同样的错误,同一行:(

TS version: 4.7.4 tsc -V TS 版本:4.7.4 tsc -V

I generally use functions to infer generic types我通常使用函数来推断泛型类型

function inferType<V extends TypeOfSomething>(t: HigherLevel<V>) { return t }

const t = inferType({ subsection: { callback: (arg: "something") => {} } })

Doubt there's another method怀疑还有别的方法

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

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