TypeScript泛型:void,never还是undefined?

时间:2016-12-22 20:40:22

标签: typescript

总是想知道这件事。所以想得到明确的答案并将其设置为石头:)

我想要做的是让编译器/语言服务/读者知道T应该是空的,空的,虚无...我想知道哪一个(voidneverundefined)是正确的/最好的。

// to indicate there should be no props available
class MyComponent extends React.Component<???, any> { ... }

// showing the Promise should resolve to nothing
function foo(): Promise<???> { ... }

(如果您能考虑其他案例,您需要考虑在泛型中使用voidneverundefined,我可以将它们添加到此列表中)< / p>

相关问题: What is the difference between never and void in typescript?

从上面的链接和@mierion-hughes的答案,never似乎很清楚。所以剩下的问题是void vs undefined

1 个答案:

答案 0 :(得分:1)

我不认为这是一个很好的答案,但无论如何你的问题有点模糊。

我认为你最接近的是使构造函数参数成为可选的T并使用nevervoid

enter image description here

此处的问题是,使用voidnever最终都会在参数类型上以undefined结尾。所以...你仍然可以通过undefined,我找不到阻止它的方法。

进一步说明:如果您不希望将属性添加到实例中,那么您需要将public放在arg上:

class Foo<T>{
  prop: T;
  constructor(prop?: T) {
    if (prop != undefined)
      this.prop = prop;
  }
}

let foo = new Foo<never>(undefined);

for (let key in foo) {
  console.log(key); //prints: nothing
}

console.log(foo);  //prints:  Foo {}