【问题标题】:How can I prevent a generic type from taking "any" as its type argument? [duplicate]如何防止泛型类型将“任何”作为其类型参数? [复制]
【发布时间】:2021-07-13 20:25:53
【问题描述】:

如何防止泛型类型将any 作为其类型参数?如果我的泛型参数使用extends 关键字进行约束,那么可以将其替换为any 感觉很奇怪。

据我了解,一切都扩展了any,但any 不应该扩展任何东西(any 本身除外)。

这是一个例子:

type OneOrTwo = 1 | 2;
type MyType<T extends OneOrTwo> = T;
const t1: MyType<OneOrTwo> = 1; // OK
const t2: MyType<any> = 2;      // OK
const t3: MyType<OneOrTwo> = 3; // Error: Type '3' is not assignable to type 'OneOrTwo';
const t4: MyType<any> = 4;      // OK?? How can I prevent this?

我可以让打字稿阻止我像这样输入t4吗?是通过更改代码还是使用tsconfig 选项?

【问题讨论】:

  • 也与How to undestand relations between types any, unknown, {} and between them and other types? 密切相关,因为您赋予any 的属性实际上对unknown 是正确的(也就是说,所有内容都扩展了unknown,但unknown 仅扩展了@987654335 @ 本身)。
  • 如果您认为上述两个问题/答案中的任何一个都不能解决您的问题,请对其进行编辑以突出差异和剩余问题。否则,我倾向于将其标记为指向它们的重复项。祝你好运!
  • @jcalz 是的。您的第二条评论中的问题特别清楚地表明,这是设计使然。谢谢!

标签: typescript typescript-generics tsconfig


【解决方案1】:

在撰写本文时,您不能。 在代码中的任何地方写 any 意味着 TypeScript 根本不做任何检查,并且这会传播。 在某些情况下,您可以通过设置以下组合来防止隐式任何:

  • 严格
  • noImplicitAny
  • stricNullCecks
  • noStrictGenericChecks
  • strictFunctionTypes
  • strictBindCallApply

tsconfig.json

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-24
    • 2019-02-27
    • 2017-11-17
    • 2019-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多