Beginner to Advanced TYPESCRIPT Swamiprasad Amin Prabhu Yadav Shashank Korthiwada Sachin Sahu
What is Typescript?  A strict syntactical superset of JavaScript, which adds type-safety to the JS code.  Free and open-source programming language developed and maintained by Microsoft.  It doesn’t change the runtime behaviour of JS. 2
Why Typescript? 3
Why Typescript?  It has the potential to move some kinds of errors from runtime to compile time. Examples include - Potentially absent values - Incomplete Refactoring  It serves as the foundation for a great code authoring experience. Note: • Only activate during development • Doesn't provide any performance optimization • In some other languages the type system can be used to optimize some code that we write using the compiler. 4
Typescript Installation  Node.js should be installed  npm install Typescript  To compile a Typescript file  npx tsc <filename>  It catches type errors in the Typescript file and creates a JavaScript file with the same name. 5
Type Systems Static vs dynamic • whether type-checking is performed at compile time or runtime. Nominal vs structural • Nominal type systems are all about NAMES, two types are deemed to be the same if they have the same name • Structural type systems are all about STRUCTURE or SHAPE TypeScript’s type system is static. TypeScript's type system is structural 6
Type Annotations • Typescript uses type annotation to specify the data type of the variable, function, object, or function return value. • It uses the syntax :[type], where type is the Typescript type. 7
Primitive types The Primitives: String, Number, Boolean • string represents string values like "Hello, world" • number is for numbers like 42. JavaScript does not have a special runtime value for integers, so there’s no equivalent to int or float - everything is simply number • boolean is for the two values true and false • It has some special types too unknown, any, void & never. Literal Types In addition to the general types string and number, we can refer to specific strings and numbers in type positions Enums Allows for describing a value which could be one of a set of possible named constants. 8
Union Types  TypeScript’s type system allows us to build new types out of existing ones using a large variety of operators.  We can achieve different use cases by combining types in interesting ways.  Syntax: We define union types by using a pipe (|) to separate each of the possible types (type1 | type2 | type3 | .. | typeN) 9
Type Aliases and Interfaces  TypeScript provides two mechanisms for centrally defining types and giving them useful and meaningful names • Interfaces • type aliases  Type aliases allows us to • define a more meaningful name for this type • declare the particulars of the type in a single place • import and export this type from modules, the same as if it were an exported value  An interface is a way of defining an object type. • Like type aliases, interfaces can be imported/exported between modules 10
Objects  Anything that is not a primitive data type is a Typescript object.  It is a collection of key-value pairs.  Each key-value pair is known as a property, where the key is the name of the property and value its value.  These provide a way to group several values into a single value.  Few ways on how types are associated for Objects • Object Literal Syntax • Named Types using Type Aliases and Interfaces 11
Arrays  Syntax for typing an array is Type[] or Array<Type>.  Here, Type can be combination of types. e.g. const list: (string | number)[] = [10, "twenty"] Tuple:  Sometimes we may want to work with a multi-element, ordered data structure, where position of each item has some special meaning or convention. e.g. type StringNumberPair = [string, number]  It can have optional properties and they come at the end.  A tuple with a rest element has no set “length” - it only has a set of well-known elements in different positions.  Tuples tend to be created and left un-modified in most code. 12
Functions  The syntax (param: string) => void means “a function with one parameter, named param, of type string, that doesn’t have a return value”.  Optional parameters can be typed with ?.  void is not the same as undefined.  When writing a function type for a callback, marking a parameter optional should be avoided unless it is intended to call the function without passing that argument.  A function, that can be called in different ways, can be typed by writing overload signatures.  If this is not inferred from code-flow analysis, it can be typed.  unknown is the type-safe counterpart of any.  The type annotation on rest parameters is implicitly any[]. 13
Classes  Fields of class can be typed and/or initialized. e.g. class Point { x: number, y = 0 }  Class constructors are very similar to functions. But, it doesn't have a return type annotation.  super must be called before accessing this in the constructor of a derived class.  implements clause is to check that a class satisfies a particular interface.  Derived classes need to follow their base class contracts. But it may choose to expose a subtype of base class with more capabilities.  Soft-private allows access using bracket notation. 14
Generics A kind of tool that enables you to create reusable code components that work with a number of types instead of a single type. <Type> parameters are for relating the types of multiple values. Type parameters can be constrained with extends keyword. Benefits:  Defining a relationship between input and output parameters types. e.g. Utility Functions  Stronger type checks at compile time will be available.  You can remove some unnecessary type casts.  You may leave type variable unassigned. 15 <T>
Utility Types Globally available types to facilitate common type transformations. Benefits:  These types are themselves strongly typed and has specific use cases. e.g. Parameters<T>, here T extends (...args: any) => any  Saves time of creating custom types for day-to-day type manipulations.  Saves you from having to think about naming your utilities. 16 Pick x Omit Readonly ReturnType NonNullable Required x Partial Extract x Extract Parameters Record
Type Manipulation  Conditional types let us deterministically define type transformations depending on a condition.  A ternary conditional operator applied at the type level rather than at the value level. 17  Mapped types are useful when there is a need for a type to be derived from (and remain in sync with) another type.  Helps us keep our types definitions that are dependent on each other code in DRY state. Conditional Types Mapped Types
Decorators  A Decorator is a special kind of declaration that can be attached to a class declaration, method, accessor, property or parameter.  Decorators provide a way to add both annotations and a meta-programming syntax for class declarations and members.  Decorators are a stage 2 proposal for JavaScript and are available as an experimental feature of TypeScript.  To enable experimental support for decorators, you must enable the experimentalDecorators compiler option either on the command line or in your tsconfig.json 18
THANK YOU

Typescript: Beginner to Advanced

  • 1.
    Beginner to Advanced TYPESCRIPT SwamiprasadAmin Prabhu Yadav Shashank Korthiwada Sachin Sahu
  • 2.
    What is Typescript? A strict syntactical superset of JavaScript, which adds type-safety to the JS code.  Free and open-source programming language developed and maintained by Microsoft.  It doesn’t change the runtime behaviour of JS. 2
  • 3.
  • 4.
    Why Typescript?  Ithas the potential to move some kinds of errors from runtime to compile time. Examples include - Potentially absent values - Incomplete Refactoring  It serves as the foundation for a great code authoring experience. Note: • Only activate during development • Doesn't provide any performance optimization • In some other languages the type system can be used to optimize some code that we write using the compiler. 4
  • 5.
    Typescript Installation  Node.jsshould be installed  npm install Typescript  To compile a Typescript file  npx tsc <filename>  It catches type errors in the Typescript file and creates a JavaScript file with the same name. 5
  • 6.
    Type Systems Static vsdynamic • whether type-checking is performed at compile time or runtime. Nominal vs structural • Nominal type systems are all about NAMES, two types are deemed to be the same if they have the same name • Structural type systems are all about STRUCTURE or SHAPE TypeScript’s type system is static. TypeScript's type system is structural 6
  • 7.
    Type Annotations • Typescriptuses type annotation to specify the data type of the variable, function, object, or function return value. • It uses the syntax :[type], where type is the Typescript type. 7
  • 8.
    Primitive types The Primitives:String, Number, Boolean • string represents string values like "Hello, world" • number is for numbers like 42. JavaScript does not have a special runtime value for integers, so there’s no equivalent to int or float - everything is simply number • boolean is for the two values true and false • It has some special types too unknown, any, void & never. Literal Types In addition to the general types string and number, we can refer to specific strings and numbers in type positions Enums Allows for describing a value which could be one of a set of possible named constants. 8
  • 9.
    Union Types  TypeScript’stype system allows us to build new types out of existing ones using a large variety of operators.  We can achieve different use cases by combining types in interesting ways.  Syntax: We define union types by using a pipe (|) to separate each of the possible types (type1 | type2 | type3 | .. | typeN) 9
  • 10.
    Type Aliases andInterfaces  TypeScript provides two mechanisms for centrally defining types and giving them useful and meaningful names • Interfaces • type aliases  Type aliases allows us to • define a more meaningful name for this type • declare the particulars of the type in a single place • import and export this type from modules, the same as if it were an exported value  An interface is a way of defining an object type. • Like type aliases, interfaces can be imported/exported between modules 10
  • 11.
    Objects  Anything thatis not a primitive data type is a Typescript object.  It is a collection of key-value pairs.  Each key-value pair is known as a property, where the key is the name of the property and value its value.  These provide a way to group several values into a single value.  Few ways on how types are associated for Objects • Object Literal Syntax • Named Types using Type Aliases and Interfaces 11
  • 12.
    Arrays  Syntax fortyping an array is Type[] or Array<Type>.  Here, Type can be combination of types. e.g. const list: (string | number)[] = [10, "twenty"] Tuple:  Sometimes we may want to work with a multi-element, ordered data structure, where position of each item has some special meaning or convention. e.g. type StringNumberPair = [string, number]  It can have optional properties and they come at the end.  A tuple with a rest element has no set “length” - it only has a set of well-known elements in different positions.  Tuples tend to be created and left un-modified in most code. 12
  • 13.
    Functions  The syntax(param: string) => void means “a function with one parameter, named param, of type string, that doesn’t have a return value”.  Optional parameters can be typed with ?.  void is not the same as undefined.  When writing a function type for a callback, marking a parameter optional should be avoided unless it is intended to call the function without passing that argument.  A function, that can be called in different ways, can be typed by writing overload signatures.  If this is not inferred from code-flow analysis, it can be typed.  unknown is the type-safe counterpart of any.  The type annotation on rest parameters is implicitly any[]. 13
  • 14.
    Classes  Fields ofclass can be typed and/or initialized. e.g. class Point { x: number, y = 0 }  Class constructors are very similar to functions. But, it doesn't have a return type annotation.  super must be called before accessing this in the constructor of a derived class.  implements clause is to check that a class satisfies a particular interface.  Derived classes need to follow their base class contracts. But it may choose to expose a subtype of base class with more capabilities.  Soft-private allows access using bracket notation. 14
  • 15.
    Generics A kind oftool that enables you to create reusable code components that work with a number of types instead of a single type. <Type> parameters are for relating the types of multiple values. Type parameters can be constrained with extends keyword. Benefits:  Defining a relationship between input and output parameters types. e.g. Utility Functions  Stronger type checks at compile time will be available.  You can remove some unnecessary type casts.  You may leave type variable unassigned. 15 <T>
  • 16.
    Utility Types Globally availabletypes to facilitate common type transformations. Benefits:  These types are themselves strongly typed and has specific use cases. e.g. Parameters<T>, here T extends (...args: any) => any  Saves time of creating custom types for day-to-day type manipulations.  Saves you from having to think about naming your utilities. 16 Pick x Omit Readonly ReturnType NonNullable Required x Partial Extract x Extract Parameters Record
  • 17.
    Type Manipulation  Conditionaltypes let us deterministically define type transformations depending on a condition.  A ternary conditional operator applied at the type level rather than at the value level. 17  Mapped types are useful when there is a need for a type to be derived from (and remain in sync with) another type.  Helps us keep our types definitions that are dependent on each other code in DRY state. Conditional Types Mapped Types
  • 18.
    Decorators  A Decoratoris a special kind of declaration that can be attached to a class declaration, method, accessor, property or parameter.  Decorators provide a way to add both annotations and a meta-programming syntax for class declarations and members.  Decorators are a stage 2 proposal for JavaScript and are available as an experimental feature of TypeScript.  To enable experimental support for decorators, you must enable the experimentalDecorators compiler option either on the command line or in your tsconfig.json 18
  • 19.