What does the `is` keyword do in typescript?

See the reference for user-defined type guard functions for more information. function isString(test: any): test is string{ return typeof test === “string”; } function example(foo: any){ if(isString(foo)){ console.log(“it is a string” + foo); console.log(foo.length); // string function } } example(“hello world”); Using the type predicate test is string in the above format (instead of just … Read more

Higher-order type functions in TypeScript?

You’re correct, it’s not currently representable in TypeScript. There’s a longstanding open GitHub feature request, microsoft/TypeScript#1213, which should probably be titled something like “support higher kinded types” but currently has the title “Allow classes to be parametric in other parametric classes”. There are some ideas in the discussion about how to simulate such higher kinded … Read more

Is there a way to define type for array with unique items in typescript?

The only possible way this could work at compile time is if your arrays are tuples composed of literals. For example, here are some arrays with the same runtime values, but with different types in TypeScript: const tupleOfLiterals: [1, 2, 2] = [1, 2, 2]; const tupleOfNonLiterals: [number, number, number] = [1, 2, 2]; const … Read more

Get properties of a class

This TypeScript code class A { private a1; public a2; } compiles to this JavaScript code class A { } That’s because properties in JavaScript start extisting only after they have some value. You have to assign the properties some value. class A { private a1 = “”; public a2 = “”; } it compiles … Read more

Difference between ‘object’ ,{} and Object in TypeScript

TypeScript has three confusing types: Object, {} and object. You can assign null and undefined to all three types if strictNullChecks compiler option is disabled otherwise the compile error occurs. Object Contains stuff (like toString(), hasOwnProperty()) that is present in all JavaScript objects. Any value (primitive, non-primitive) can be assigned to Object type. {} {} … Read more