TypeScript - KeynesYouDigIt/Knowledge GitHub Wiki
- Every project should have a
tsconfig.jsonthat says where the src files are, where the build files should go, what browsers should be targeted, etc. -
tslintis deprecated in favor ofeslint - Prefer local ts installations
- `npm i -D typescript @types/node
- Built-ins -
number,boolean,undefined,string,object(non-primative)-
nullandundefinedare legal values for any other type (disablable)
-
- New types:
-
:any- Disables type checking void- Arrays: can be done as
number[]orArray<number> - Tuples:
let x = [string, number, string] - Enum:
enum Color {Red, Green, Blue}- Keeps numeric values
let color: Color = Color.Green; // 1
-
never: Errors, things that should never be called -
ReadonlyArray<TypeGoesHere>: No mutation methods
-
Don't need to declare the object has having implemented the interface.
interface Person {
name: string;
optional?: boolean; // Optional property
readonly dontWriteMe: string; // Like const for properties
[propName: string]: any; // Any other properties
}
function announcePerson(person: Person) {
}interface SendMessage {
(recipient: Person, message: string): void
}
let messageFunction: SendMessage
messageFunction = function(recipient: Person, message: string): void {
//
};Comes after
const { old: new } : { old: number} = { old: 1 }Make a type (like any) more specific.
let aString: any = "hey";
let aStringLength = (aString as string)or
let aString: any = "hey";
let aStringLength = (<string>aString).length;tsc
-
--strictNullChecks- Saves a lot of headaches
- When importing modules, use
npm i -D @types/package-nameto use prebuilt type definitions- If it doesn't exist, put the following in a file to declare it as
any:
- If it doesn't exist, put the following in a file to declare it as
// package-name.d.ts
declare module "package-name";