Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript generics: void, never, or undefined? [closed]

Tags:

typescript

Always wondering about this. So want to get a definite answer and set it to stone :)

What I want to do is to let the compiler/language service/reader knows that T should be nothing, empty, nada. I want to know which one (void, never, undefined) is the right / best one to use.

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

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

( let me know if you can think of other cases you need to think about using void, never, or undefined in generics and I can add them to this list )

Related questions: What is the difference between never and void in typescript?

From the above link, and the answer from @mierion-hughes, never seems to be clear. So the remaining question is void vs undefined

like image 456
unional Avatar asked Nov 01 '25 02:11

unional


1 Answers

I don't think this is a good answer, but your question is a little vague anyway.

I think the closest you'll get is to make the constructor argument optional T and use never or void.

enter image description here

the problem here is that using void or never both end up as undefined on the argument type. So... you can still pass undefined, and I cannot see a way to stop that.

Taking it a little further: If you don't want the property added to the instance, then you would need to drop the public on the 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 {}
like image 96
Meirion Hughes Avatar answered Nov 03 '25 02:11

Meirion Hughes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!