Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript equivalent to C#'s default<T>?

Tags:

typescript

In Typescript, is there an equivalent to default?

If not, can its behaviour be implemented somehow?

example:

 let myNumber = default<Number>(); // 0
 let myInstance = default<MyClass>(); // null
like image 842
Serge Intern Avatar asked May 08 '17 06:05

Serge Intern


People also ask

Can JavaScript run C code?

js can dynamically load an external C or C++ DLL file at runtime and utilize its API to perform some operations written inside it from a JavaScript program. This is basically how a Native Addon works in Node. js.

What is use of in JS?

The JavaScript in operator is used to check if a specified property exists in an object or in its inherited properties (in other words, its prototype chain). The in operator returns true if the specified property exists. Anatomy of a simple JavaScript object.


1 Answers

No, there is no such thing in TypeScript:

  • If the strictNullChecks flag is set, each type (including user-defined) would need its own default instance, which is not practical

  • If it is unset, the default value for everything is undefined so there would be no point having a special default operator

If you need this behaviour you will have to define default functions yourself for each type that you need - and even then, you will not be able to use them generically because generic type information is not preserved at runtime

like image 186
Alex Avatar answered Oct 25 '22 07:10

Alex