## Basic types (Typescript) 🔹 *parent* [[⧋ Typescript|Typescript]] ▫️ *related* [[⏶ Union types|Union types]], [[Decorators and Dynamic Behavior (Typescript)|Decorators]], [[Module basics|Module basics]] ### Basic types ```ts let x: number let y: string let z: boolean let a: Date let b: string[] // string array b = "hello" // throws error b = "hello" as any // can be converted to 'any' type ``` ### Custom types with Interfaces ```ts interface Contact { id: number; name: string; birthDate: Date; optionalField?: number; // lets you tell if a field will be optional, but if it is present, it must be the type specified } let primaryContact: Contact = { birthDate: new Date("01-01-1980"), id: 12345, name: "Jamie", birthDate: "01-01-1980" // throws error } ``` You can also `extend` an `interface` ```ts interface Contact extends Address { id: number; name: string; birthDate: Date; } interface Address { line1: string; line2: string; province: string; region: string; postalCode: string; } ``` You can also define *type aliases* ```ts interface Contact { name: ContactName; // compiles as string } type ContactName = string ``` Defining *enumerable types* ```ts interface Contact { status: ContactStatus; // this will only allow [Active, Inactive, New] } enum ContactStatus { Active, // or Active = "active" Inactive, New } let primaryContact: Contact = { status: ContactStatus.Active // ContactStatus = 0 || ContactStatus = "active" } ``` ### Typing functions The type defined after the function definition will define what it expects to return. Because of this, you can use this to define what type will be cloned. ```ts interface Contact { id: number; name: string; } // in order for clone(a) to work, function:Contact must be defined after the function definition, not just in the argument. function clone(source:Contact):Contact { return Object.apply({}, source) } const a: Contact = {id: 1234, name: "Homer"}; const b = clone(a) ``` ### Generic Types You can uses `<T>` in the function name to define a *generic type*, which can then be used in the argument and after the function definiton. You can also use `<T1>` and `<T2>` to define multiple interface definitions for a single function. ```ts interface Contact { id: number; name: string; } interface UserContact { id: number; name: string; username: string; } function clone<T>(source: T): T { return Object.apply({}, source) } function clone2<T1, T2 extends T1>(source: T1): T2{ return Object.apply({}, source) } const a: Contact = {id: 1234, name: "Homer"}; const b = clone(a) // clone will copy original 'a' so clone:Contact(source: Contact): Contact const c = clone2<Contact, UserContact>(dateRange) const dateRange = { startDate: Date:now(), endDate: Date.now() } const dateRangeCopy = clone(dateRange) ``` ### References See [[⧋ Typescript#References|Typescript References]]