let value: string | number;
value = 'hello';
value = 123;
function print(id: string | number) {
console.log(id);
}
interface Person {
name: string;
}
interface Employee {
id: number;
}
type Staff = Person & Employee;
let staff: Staff = {
name: 'John',
id: 1001
};
function print(value: string | number) {
if (typeof value === 'string') {
console.log(value.toUpperCase());
} else {
console.log(value.toFixed(2));
}
}
class Dog {
bark() {
console.log('汪汪');
}
}
class Cat {
meow() {
console.log('喵喵');
}
}
function makeSound(animal: Dog | Cat) {
if (animal instanceof Dog) {
animal.bark();
} else {
animal.meow();
}
}
interface Bird {
fly(): void;
}
interface Fish {
swim(): void;
}
function move(animal: Bird | Fish) {
if ('fly' in animal) {
animal.fly();
} else {
animal.swim();
}
}
interface Bird {
fly(): void;
}
interface Fish {
swim(): void;
}
function isBird(animal: Bird | Fish): animal is Bird {
return (animal as Bird).fly !== undefined;
}
function move(animal: Bird | Fish) {
if (isBird(animal)) {
animal.fly();
} else {
animal.swim();
}
}
interface Square {
kind: 'square';
size: number;
}
interface Rectangle {
kind: 'rectangle';
width: number;
height: number;
}
interface Circle {
kind: 'circle';
radius: number;
}
type Shape = Square | Rectangle | Circle;
function area(shape: Shape): number {
switch (shape.kind) {
case 'square':
return shape.size * shape.size;
case 'rectangle':
return shape.width * shape.height;
case 'circle':
return Math.PI * shape.radius ** 2;
}
}
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
let user = {
name: 'John',
age: 25
};
let name = getProperty(user, 'name');
let age = getProperty(user, 'age');
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
type Partial<T> = {
[P in keyof T]?: T[P];
};
interface User {
name: string;
age: number;
}
type ReadonlyUser = Readonly<User>;
type PartialUser = Partial<User>;
T extends U ? X : Y
type IsString<T> = T extends string ? true : false;
type A = IsString<string>;
type B = IsString<number>;
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;
function getUser() {
return { name: 'John', age: 25 };
}
type User = ReturnType<typeof getUser>;
type World = 'world';
type Greeting = `hello ${World}`;
type EventName<T extends string> = `on${Capitalize<T>}`;
type ClickEvent = EventName<'click'>;
type Direction = 'left' | 'right' | 'top' | 'bottom';
type Margin = `margin${Capitalize<Direction>}`;
type ID = string | number;
type User = {
id: ID;
name: string;
age: number;
};
type Callback = (data: string) => void;
let value: unknown = 'hello';
let length = (value as string).length;
let name: string | null = getName();
let upper = name!.toUpperCase();
let obj = { name: 'John' } as const;
let num = 123;
let str = 'hello';
let arr = [1, 2, 3];
let mixed = [1, 'hello'];
window.onmousedown = function(event) {
};