enum HttpStatus {
OK = 200,
Created = 201,
BadRequest = 400,
NotFound = 404,
}
function logStatus(status: HttpStatus) {
console.log(`${HttpStatus[status]}: ${status}`);
}
logStatus(HttpStatus.OK);
enum FileAccess {
Read = 'read',
Write = 'write',
Execute = 'execute',
}
console.log(FileAccess.Write);
let tupleType: [string, boolean];
tupleType = ["semlinker", true];
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
function myFunc(maybeString: string | undefined | null) {
const onlyString: string = maybeString;
const ignoreUndefinedAndNull: string = maybeString!;
}
interface Admin {
name: string;
privileges: string[];
}
interface Employee {
name: string;
startDate: Date;
}
type UnknownEmployee = Employee | Admin;
function printEmployeeInformation(emp: UnknownEmployee) {
console.log("Name: " + emp.name);
if ("privileges" in emp) {
console.log("Privileges: " + emp.privileges);
}
if ("startDate" in emp) {
console.log("Start Date: " + emp.startDate);
}
}
function padLeft(value: string, padding: string | number) {
if (typeof padding === "number") {
return Array(padding + 1).join(" ") + value;
}
if (typeof padding === "string") {
return padding + value;
}
throw new Error(`Expected string or number, got '${padding}'.`);
}
interface Padder {
getPaddingString(): string;
}
class SpaceRepeatingPadder implements Padder {
constructor(private numSpaces: number) { }
getPaddingString() {
return Array(this.numSpaces + 1).join(" ");
}
}
class StringPadder implements Padder {
constructor(private value: string) { }
getPaddingString() {
return this.value;
}
}
let padder: Padder = new SpaceRepeatingPadder(6);
if (padder instanceof SpaceRepeatingPadder) {
}
const sayHello = (name: string | undefined) => {
};
let num: 1 | 2 = 1;
type EventNames = 'click' | 'scroll' | 'mousemove';
type PartialPointX = { x: number; };
type Point = PartialPointX & { y: number; };
let point: Point = {
x: 1,
y: 1
}
function createUserId(
name: string = "semlinker",
id: number,
age?: number
): string {
return name + id;
}
function push(array, ...items) {
items.forEach(function (item) {
array.push(item);
});
}
let a = [];
push(a, 1, 2, 3);
function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: string, b: number): string;
function add(a: number, b: string): string;
function add(a: Combinable, b: Combinable) {
if (typeof a === 'string' || typeof b === 'string') {
return a.toString() + b.toString();
}
return a + b;
}
let x: number; let y: number; let z: number;
let five_array = [0, 1, 2, 3, 4];
[x, y, z] = five_array;
console.log(x, y, z)
let two_array = [0, 1];
let five_array = [...two_array, 2, 3, 4];
let colors: string[] = ["red", "green", "blue"];
for (let i of colors) {
console.log(i);
}
interface Person {
name: string;
age: number;
}
let semlinker: Person = {
name: "semlinker",
age: 33,
};
interface Person {
readonly name: string;
age?: number;
}
interface Person {
name: string;
age?: number;
[propName: string]: any;
}
const p1 = { name: "semlinker" };
const p2 = { name: "lolo", age: 5 };
const p3 = { name: "kakuqo", sex: 1 }
interface Point {
x: number;
y: number;
}
interface SetPoint {
(x: number, y: number): void;
}
type Name = string;
type PartialPointX = { x: number; };
type PartialPointY = { y: number; };
type PartialPoint = PartialPointX | PartialPointY;
type Data = [number, string];
class Greeter {
static cname: string = "Greeter";
greeting: string;
constructor(message: string) {
this.greeting = message;
}
static getClassName() {
return "Class name is Greeter";
}
greet() {
return "Hello, " + this.greeting;
}
}
let greeter = new Greeter("world");
let passcode = "Hello TypeScript";
class Employee {
private _fullName: string;
get fullName(): string {
return this._fullName;
}
set fullName(newName: string) {
if (passcode && passcode == "Hello TypeScript") {
this._fullName = newName;
} else {
console.log("Error: Unauthorized update of employee!");
}
}
}
let employee = new Employee();
employee.fullName = "Semlinker";
if (employee.fullName) {
console.log(employee.fullName);
}
class ProductService {
getProducts(): void;
getProducts(id: number): void;
getProducts(id?: number) {
if (typeof id === 'number') {
console.log(`获取id为 ${id} 的产品信息`);
} else {
console.log(`获取所有的产品信息`);
}
}
}
const productService = new ProductService();
productService.getProducts(666);
productService.getProducts();
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}
let myGenericNumber = new GenericNumber<number>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function (x, y) {
return x + y;
};
interface Person {
name: string;
age: number;
}
const sem: Person = { name: 'semlinker', age: 33 };
type Sem = typeof sem;
function toArray(x: number): Array<number> {
return [x];
}
type Func = typeof toArray;
interface Person {
name: string;
age: number;
}
type K1 = keyof Person;
type K2 = keyof Person[];
type K3 = keyof { [x: string]: Person };
type Keys = "a" | "b" | "c"
type Obj = {
[p in Keys]: any
}
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}
`Partial<T>` 的作用就是将某个类型里的属性全部变为可选项 `?`。
interface Todo {
title: string;
description: string;
}
function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
return { ...todo, ...fieldsToUpdate };
}
const todo1 = {
title: "Learn TS",
description: "Learn TypeScript",
};
const todo2 = updateTodo(todo1, {
description: "Learn TypeScript Enum",
});
{
title?: string | undefined;
description?: string | undefined;
}