100 Type Script Concepts
100 Type Script Concepts
3- Tuple: Tuples are arrays where the type of a fixed number of elements
is known.
8- Never: The never type represents the type of values that never
occur.
10- Type Assertions: A way to tell the compiler "trust me, I know what
I'm doing."
interface LabelledValue {
label: string;
}
function printLabel(labelledObj: LabelledValue) {
console.log(labelledObj.label);
}
interface SquareConfig {
color?: string;
width?: number;
}
interface Point {
readonly x: number;
readonly y: number;
}
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc;
mySearch = function(source: string, subString: string) {
return source.search(subString) > -1;
}
15- Indexable Types: We can describe types that we can "index into",
like a[10], or ageMap["daniel"].
interface StringArray {
[index: number]: string;
}
let myArray: StringArray;
myArray = ["Bob", "Fred"];
interface ClockInterface {
currentTime: Date;
}
class Clock implements ClockInterface {
currentTime: Date = new Date();
}
interface Shape {
color: string;
}
interface Square extends Shape {
sideLength: number;
}
let square = <Square>{};
square.color = "blue";
square.sideLength = 10;
interface Counter {
(start: number): string;
interval: number;
reset(): void;
}
class Control {
private state: any;
}
interface SelectableControl extends Control {
select(): void;
}
class Animal {
move(distanceInMeters: number = 0) {
console.log(`Animal moved ${distanceInMeters}m.`);
}
}
class Dog extends Animal {
bark() {
console.log('Woof! Woof!');
}
}
class Animal {
public name: string;
private type: string;
protected age: number;
}
22- Readonly modifier: You can make properties readonly with the
readonly keyword.
class Octopus {
readonly name: string;
constructor (theName: string) {
this.name = theName;
}
}
class Grid {
static origin = {x: 0, y: 0};
}
24- Abstract Classes: Abstract classes are base classes from which
other classes may be derived.
26- Function Types: We can add types to each of the parameters and then
to the function itself to add a return type.
let myAdd: (x: number, y: number) => number = function(x: number, y: number):
number {
return x+y;
};
29- this parameters: TypeScript lets you ensure that the this is what
you expect it to be within a function with a this parameter.
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}
let x = foo?.bar.baz();
41- instanceof type guards: The instanceof type guards are useful when
working with classes.
42- typeof type guards: typeof type guards are handy when dealing with
primitive types.
43- Literal Types: Literal types allow you to specify the exact value a
variable must have.
interface Bird {
type: 'bird';
flyingSpeed: number;
}
interface Horse {
type: 'horse';
runningSpeed: number;
}
class Disposable {
isDisposed: boolean;
dispose() {
// ...
}
}
type TypeName<T> =
T extends string ? "string" :
T extends number ? "number" :
T extends boolean ? "boolean" :
T extends undefined ? "undefined" :
T extends Function ? "function" :
"object";
48- Mapped Types: A mapped type is a generic type which uses a union
created via a keyof to iterate through the keys of one type to create
another.
type Readonly<T> = {
readonly [P in keyof T]: T[P];
}
@sealed
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
@enumerable(false)
greet() {
return "Hello, " + this.greeting;
}
}
@DisposableMixin
@ActivatableMixin
class SmartObject {
// ...
}
interface Named {
name: string;
}
let x: Named;
let y = { name: "Alice", location: "Seattle" };
x = y;
57- Iterators and Generators: Objects that have a next method which
returns the result object {done, value}.
{
"compilerOptions": {
"module": "system",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"outFile": "../../built/local/tsc.js",
"sourceMap": true
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"**/*.spec.ts"
]
}
61- TypeScript with Babel: TypeScript can work with Babel using the
@babel/preset-typescript.
{
"presets": [
"@babel/preset-env",
"@babel/preset-typescript"
]
}
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
}
63- TypeScript with ESLint: TypeScript can work with ESLint using
@typescript-eslint/parser.
{
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
]
}
64- Using tsc command line: The tsc command line utility to compile
TypeScript code.
tsc index.ts
67- Type Inference: TypeScript tries to infer the types when there are
no explicit types specified.
68- Type Assertions: Sometimes you will know more about a value than
TypeScript does and you would need to assert the type.
let x: number = 1;
console.log(typeof x); // 'number', not 'Number'
70- Type Predicates: A special kind of type that can be returned from a
function's signature.
71- Optional Properties in Classes: You can use the optional modifier ?
to indicate properties that might not exist.
class User {
username: string;
password?: string;
}
interface AppProps {
title: string;
}
enum Color {
Red,
Green,
Blue
}
let c: Color = Color.Green;
74- Never Type: The never type represents the type of values that never
occur.
75- Namespace: Namespaces are used to organize code and avoid naming
collisions.
namespace Validation {
export interface StringValidator {
isAcceptable(s: string): boolean;
}
}
76- Module: Modules are executed within their own scope, not in the
global scope.
@Reflect.metadata(metadataKey, metadataValue)
class MyClass {
}
type Readonly<T> = {
readonly [P in keyof T]: T[P];
}
interface Cloner {
clone(animal: Animal): Animal;
}
interface Cloner {
clone(animal: Sheep): Sheep;
}
85- Using tsc --init to generate a tsconfig.json file: tsc --init creates
a new tsconfig.json file in the current directory with default options.
tsc --init
@Component({
selector: 'my-app',
template: '<h1>Hello {{name}}</h1>',
})
export class AppComponent { name = 'Angular'; }
92- Working with Type Guards: A type guard is some expression that
performs a runtime check that guarantees the type in some scope.
function myForEach(arr: any[], callback: (arg: any, index?: number) => void)
{
for(let i = 0; i < arr.length; i++) {
callback(arr[i], i);
}
}
95- Type Aliases: Type aliases create a new name for a type.
96- String Literal Types: String literal types allow you to specify the
exact value a string must have.
97- Numeric Literal Types: TypeScript also has numeric literal types.
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
declare global {
interface Array<T> {
toObservable(): Observable<T>;
}
}
100- Triple Equals vs Double Equals: === is the equality operator, and
== is the loose equality operator.
let x: any = 0;
console.log(x == false); // True, loose equality
console.log(x === false); // False, strict equality
{
"compilerOptions": {
"outDir": "../out",
"rootDir": "../",
"composite": true
},
"references": [
{ "path": "../core" },
{ "path": "../types" }
]
}