Skip to content

Instantly share code, notes, and snippets.

@makstaks
Last active August 29, 2017 03:28
Show Gist options
  • Select an option

  • Save makstaks/df087beff28347448820c32ea6d8a1c4 to your computer and use it in GitHub Desktop.

Select an option

Save makstaks/df087beff28347448820c32ea6d8a1c4 to your computer and use it in GitHub Desktop.
Typescript Basic Types
/**
* Typescript 2.4
*
* Last updated: 2017-08-23
* Examples from: https://www.typescriptlang.org/docs/handbook/basic-types.html
* 1 Basic Types
* 1.1 Boolean
* 1.2 Number
* 1.3 String
* 1.4 Arrays
* 1.5 Tuple
* 1.6 Enum
* 1.7 Any
* 1.8 Void
* 1.9 Null and Undefined - TODO
* 1.10 Never - TODO
* 1.11 Type Assertions
*/
/** 1.1 Declaring boolean */
let isDone: boolean = false;
/**
* 1.2 Number
* All numbers in TypeScript are floating point values.
*/
let decimal: number = 6;
let hex: number = 0xf00d;
let binary: number = 0b1010;
let octal: number = 0o744;
/** 1.3 String */
let color: string = "blue";
color = 'red';
/**
* Template strings
* You can also use template strings, which can span multiple lines and have embedded expressions.
*/
let fullName: string = `Bob Bobbington`;
let age: number = 37;
let sentence: string = `Hello, my name is ${ fullName }.
I'll be ${ age + 1 } years old next month.`;
/** 1.4 Arrays */
// You use the type of the elements followed by [] to denote an array of that element type:
let list: number[] = [1, 2, 3];
//The second way uses a generic array type, Array<elemType>:
let list: Array<number> = [1, 2, 3];
/**
* 1.5 Tuple
* Tuple types allow you to express an array where the type of
* a fixed number of elements is known, but need not be the same.
*/
// For example, you may want to represent a value as a pair of a string and a number:
let x: [string, number];
//Initialize it
x = ["hello", 10]; // OK
// Initialize it incorrectly
x = [10, "hello"]; // Error
// When accessing an element with a known index, the correct type is retrieved:
console.log(x[0].substr(1)); // OK
console.log(x[1].substr(1)); // Error, 'number' does not have 'substr'
// When accessing an element outside the set of known indices, a union type is used instead:
x[3] = "world"; // OK, 'string' can be assigned to 'string | number'
console.log(x[5].toString()); // OK, 'string' and 'number' both have 'toString'
x[6] = true; // Error, 'boolean' isn't 'string | number'
/** 1.6 Enum */
enum Color {Red, Green, Blue}
let c: Color = Color.Green;
// By default, enums begin numbering their members starting at 0.
// You can change this by manually setting the value of one of its members.
// For example, we can start the previous example at 1 instead of 0:
enum Color {Red = 1, Green, Blue}
let c: Color = Color.Green;
// Or, even manually set all the values in the enum:
enum Color {Red = 1, Green = 2, Blue = 4}
let c: Color = Color.Green;
// Getting Enum by value
enum Color {Red = 1, Green, Blue}
let colorName: string = Color[2];
alert(colorName);
/**
* 1.7 Any
* We may need to describe the type of variables that we do not know
* when we are writing an application. These values may come from dynamic content,
* e.g. from the user or a 3rd party library.
*/
// In these cases, we want to opt-out of type-checking and
//let the values pass through compile-time checks. To do so, we label these with the any type:
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean
// The any type is a powerful way to work with existing JavaScript,
// allowing you to gradually opt-in and opt-out of type-checking during compilation.
// You might expect Object to play a similar role, as it does in other languages.
// But variables of type Object only allow you to assign any value to them - you can’t call arbitrary methods on them, even ones that actually exist:
let notSure: any = 4;
notSure.ifItExists(); // okay, ifItExists might exist at runtime
notSure.toFixed(); // okay, toFixed exists (but the compiler doesn't check)
let prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.
// The any type is also handy if you know some part of the type, but perhaps not all of it.
// For example, you may have an array but the array has a mix of different types:
let list: any[] = [1, true, "free"];
list[1] = 100;
/** 1.8 Void */
// void is a little like the opposite of any: the absence of having any type at all.
// You may commonly see this as the return type of functions that do not return a value:
function warnUser(): void {
alert("This is my warning message");
}
// Declaring variables of type void is not useful because you can only assign undefined or null to them:
let unusable: void = undefined;
/** 1.9 Null and Undefined */
// In TypeScript, both undefined and null actually have their own types named undefined and null respectively.
// Much like void, they’re not extremely useful on their own:
// Not much else we can assign to these variables!
let u: undefined = undefined;
let n: null = null;
// By default null and undefined are subtypes of all other types.
// That means you can assign null and undefined to something like number.
// However, when using the --strictNullChecks flag, null and undefined are only assignable to void
// and their respective types. This helps avoid many common errors.
// In cases where you want to pass in either a string or null or undefined,
// you can use the union type string | null | undefined. Once again, more on union types later on.
// As a note: we encourage the use of --strictNullChecks when possible,
// but for the purposes of this handbook, we will assume it is turned off.
/** 1.10 Never
// ???
// 1.11 Type assertions
// A type assertion is like a type cast in other languages,
// but performs no special checking or restructuring of data.
// It has no runtime impact, and is used purely by the compiler.
// TypeScript assumes that you, the programmer, have performed any special checks that you need.
// Type assertions have two forms. One is the “angle-bracket” syntax:
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
// And the other is the as-syntax:
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
// NOTE: The two samples are equivalent.
// Using one over the other is mostly a choice of preference;
// however, when using TypeScript with JSX, only as-style assertions are allowed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment