在 TypeScript 中,内置函数分为两类:JavaScript 原生函数(TypeScript 继承)和TypeScript 特有函数(类型系统相关)。以下是详细分类介绍:
一、JavaScript 原生函数
TypeScript 继承了所有 JavaScript 内置对象和方法,按对象分类如下:
1. 全局对象函数
// 类型转换
const num: number = parseInt("10", 10); // 10
const float: number = parseFloat("3.14"); // 3.14
const str: string = String(42); // "42"
const bool: boolean = Boolean(0); // false
// 数学运算
const abs: number = Math.abs(-5); // 5
const pow: number = Math.pow(2, 3); // 8
const random: number = Math.random(); // 0-1 随机数
// 日期处理
const now: Date = new Date();
const year: number = now.getFullYear(); // 当前年份
const formatted: string = now.toISOString(); // 格式化日期
2. 数组方法
const arr: number[] = [1, 2, 3];
// 遍历与转换
const doubled: number[] = arr.map(x => x * 2); // [2, 4, 6]
const filtered: number[] = arr.filter(x => x > 1); // [2, 3]
const sum: number = arr.reduce((acc, x) => acc + x, 0); // 6
// 查找与判断
const found: number | undefined = arr.find(x => x === 2); // 2
const hasEven: boolean = arr.some(x => x % 2 === 0); // true
const allPositive: boolean = arr.every(x => x > 0); // true
// 修改数组
const sliced: number[] = arr.slice(0, 2); // [1, 2]
const spliced: number[] = arr.splice(1, 1); // 删除索引1,返回 [2]
const joined: string = arr.join("-"); // "1-3"
3. 字符串方法
const str: string = "Hello, TypeScript!";
const length: number = str.length; // 17
const subStr: string = str.substring(7, 11); // "Type"
const index: number = str.indexOf("Type"); // 7
const replaced: string = str.replace("Type", "JavaScript"); // "Hello, JavaScript!"
const upper: string = str.toUpperCase(); // "HELLO, TYPESCRIPT!"
const trimmed: string = " abc ".trim(); // "abc"
4. 对象方法
const obj = { a: 1, b: 2 };
const keys: string[] = Object.keys(obj); // ["a", "b"]
const values: number[] = Object.values(obj); // [1, 2]
const entries: [string, number][] = Object.entries(obj); // [["a", 1], ["b", 2]]
const cloned: typeof obj = Object.assign({}, obj); // 浅拷贝
const frozen: typeof obj = Object.freeze(obj); // 冻结对象
5. 异步函数
// Promise
const fetchData = (): Promise<string> => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve("Data"), 1000);
});
};
// async/await
async function getData() {
try {
const data = await fetchData();
return data;
} catch (error) {
console.error(error);
}
}
// 定时器
setTimeout(() => console.log("Delayed"), 1000);
const interval = setInterval(() => console.log("Every second"), 1000);
clearInterval(interval); // 清除定时器
二、TypeScript 特有函数
这些函数主要用于类型操作和编译时检查。
1. 类型守卫(Type Guards)
// typeof 守卫
function printValue(x: string | number) {
if (typeof x === "string") {
console.log(x.toUpperCase()); // x 被收窄为 string
} else {
console.log(x.toFixed(2)); // x 被收窄为 number
}
}
// instanceof 守卫
class Dog { bark() {} }
class Cat { meow() {} }
function petSound(animal: Dog | Cat) {
if (animal instanceof Dog) {
animal.bark(); // animal 被收窄为 Dog
} else {
animal.meow(); // animal 被收窄为 Cat
}
}
// 用户自定义守卫
function isNumber(x: any): x is number {
return typeof x === "number";
}
2. 类型断言(Type Assertion)
const value: any = "hello";
const length: number = (value as string).length; // 断言为 string
// 非空断言
const element: HTMLElement | null = document.getElementById("app");
element!.innerHTML = "Hello"; // 断言 element 非空
3. 泛型函数
function identity<T>(arg: T): T {
return arg;
}
const num: number = identity(10);
const str: string = identity("hello");
4. 工具类型
// Partial<T> - 创建可选类型
type User = { name: string; age: number };
type PartialUser = Partial<User>; // { name?: string; age?: number }
// Readonly<T> - 创建只读类型
type ReadonlyUser = Readonly<User>; // 所有属性只读
// Pick<T, K> - 选取部分属性
type NameOnly = Pick<User, "name">; // { name: string }
// Omit<T, K> - 排除部分属性
type AgeOnly = Omit<User, "name">; // { age: number }
// Exclude<T, U> - 从 T 中排除 U
type NonNumber = Exclude<string | number, number>; // string
5. 装饰器(Decorators)
// 类装饰器
function log(target: Function) {
console.log(`Class ${target.name} was created`);
}
@log
class MyClass {}
// 方法装饰器
function readonly(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
descriptor.writable = false;
}
class Example {
@readonly
method() {}
}
三、DOM/Browser API
TypeScript 为浏览器环境提供了类型定义:
// DOM 操作
const element: HTMLElement | null = document.getElementById("app");
if (element) {
element.textContent = "Hello";
element.addEventListener("click", (event: MouseEvent) => {
console.log(event.clientX);
});
}
// Fetch API
async function fetchData() {
const response: Response = await fetch("https://api.example.com/data");
const data: any = await response.json();
return data;
}
四、其他实用函数
// 解构赋值
const { name, age } = { name: "Alice", age: 30 };
// 扩展运算符
const arr1 = [1, 2];
const arr2 = [...arr1, 3]; // [1, 2, 3]
// 可选链操作符
const user = { address: { city: "New York" } };
const city: string | undefined = user?.address?.city;
// 空值合并操作符
const value: string = null ?? "default"; // "default"
在游戏中的使用举例
在H5游戏开发中,TypeScript 的内置函数和类型系统特性可大幅提升开发效率和代码质量。以下是内置函数在游戏开发中的具体应用场景及示例:
五、游戏开发中原生函数的应用
1. 数学与随机数(游戏逻辑)
// 生成随机位置
function getRandomPosition(min: number, max: number): number {
return Math.random() * (max - min) + min; // 内置 Math.random
}
// 计算两点间距离
function calculateDistance(x1: number, y1: number, x2: number, y2: number): number {
return Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); // 内置 Math.sqrt/pow
}
// 角度转弧度(常用于旋转计算)
const angleInRadians: number = (45 * Math.PI) / 180; // 内置 Math.PI
2. 数组操作(实体管理)
class GameObject {
constructor(public x: number, public y: number) {}
}
const gameObjects: GameObject[] = [];
// 添加对象
gameObjects.push(new GameObject(100, 200));
// 更新所有对象位置
gameObjects.forEach(obj => {
obj.x += 5; // 内置 Array.forEach
});
// 过滤可见对象
const visibleObjects = gameObjects.filter(obj => obj.x > 0 && obj.x < 800); // 内置 Array.filter
3. 定时器与动画(游戏循环)
// 游戏主循环(使用 requestAnimationFrame)
function gameLoop(timestamp: number) {
updateGameState();
render();
requestAnimationFrame(gameLoop); // 内置浏览器 API
}
// 启动游戏
requestAnimationFrame(gameLoop);
// 延迟执行(如技能冷却)
function activateSkill() {
// 技能激活
setTimeout(() => {
// 冷却结束
}, 3000); // 内置 setTimeout
}
4. 对象操作(配置管理)
// 游戏配置合并
const defaultConfig = {
volume: 0.8,
difficulty: "medium",
graphics: "high"
};
const userConfig = { difficulty: "hard" };
const finalConfig = { ...defaultConfig, ...userConfig }; // 内置对象扩展
5. 类型系统(实体建模)
// 游戏角色接口
interface Character {
name: string;
health: number;
attack(): void;
}
// 实现类
class Warrior implements Character {
constructor(public name: string, public health: number = 100) {}
attack() {
console.log(`${this.name} 挥剑攻击!`);
}
}
// 类型守卫(判断角色类型)
function isWarrior(character: Character): character is Warrior {
return 'name' in character;
}
6. 泛型(组件复用)
// 通用状态管理器
class StateManager<T> {
constructor(private state: T) {}
getState(): T {
return this.state;
}
setState(newState: Partial<T>): void {
this.state = { ...this.state, ...newState };
}
}
// 使用示例
const playerState = new StateManager({ health: 100, level: 1 });
playerState.setState({ health: 80 }); // 更新部分状态
7. 装饰器(行为增强)
// 日志装饰器(记录方法调用)
function logMethod(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
console.log(`Calling ${propertyKey} with args: ${JSON.stringify(args)}`);
return originalMethod.apply(this, args);
};
return descriptor;
}
class Player {
@logMethod
attack(enemy: string) {
console.log(`${this.name} attacks ${enemy}`);
}
}
8. 工具类型(简化开发)
// 从接口创建可选配置
interface Weapon {
name: string;
damage: number;
durability: number;
}
type WeaponConfig = Partial<Weapon>; // 所有属性可选
// 创建只读常量
const readonlyConfig: Readonly<WeaponConfig> = { name: "Sword", damage: 10 };
// readonlyConfig.damage = 20; // 错误:无法修改只读属性
六、DOM/Browser API 应用(前端游戏)
1. Canvas 渲染
// 获取 Canvas 上下文
const canvas = document.getElementById("gameCanvas") as HTMLCanvasElement;
const ctx = canvas.getContext("2d");
// 绘制矩形(玩家)
function drawPlayer(x: number, y: number, width: number, height: number) {
ctx.fillStyle = "blue";
ctx.fillRect(x, y, width, height); // 内置 Canvas API
}
// 监听键盘事件(控制玩家)
document.addEventListener("keydown", (event: KeyboardEvent) => {
if (event.key === "ArrowRight") {
// 向右移动
}
});
2. 事件系统
// 自定义事件管理器
class EventEmitter {
private listeners: { [event: string]: Function[] } = {};
on(event: string, callback: Function) {
if (!this.listeners[event]) this.listeners[event] = [];
this.listeners[event].push(callback);
}
emit(event: string, ...args: any[]) {
if (this.listeners[event]) {
this.listeners[event].forEach(callback => callback(...args));
}
}
}
// 使用示例
const gameEvents = new EventEmitter();
gameEvents.on("playerDeath", () => console.log("Game Over"));
七、异步操作(资源加载)
// 异步加载图片资源
async function loadImage(url: string): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = url;
});
}
// 并行加载多个资源
async function loadAssets() {
const [background, playerSprite, enemySprite] = await Promise.all([
loadImage("bg.png"),
loadImage("player.png"),
loadImage("enemy.png")
]);
// 资源加载完成后初始化游戏
initGame(background, playerSprite, enemySprite);
}
八、实际游戏开发框架示例
1. Phaser 3 + TypeScript
import Phaser from "phaser";
class MyGame extends Phaser.Scene {
private player!: Phaser.Physics.Arcade.Sprite;
constructor() {
super("GameScene");
}
preload() {
this.load.image("player", "assets/player.png"); // 内置加载器
}
create() {
this.player = this.physics.add.sprite(400, 300, "player"); // 物理引擎
this.physics.world.setBounds(0, 0, 800, 600); // 世界边界
}
update() {
// 游戏逻辑更新
if (this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.RIGHT).isDown) {
this.player.setVelocityX(200); // 移动控制
}
}
}
// 游戏配置
const config: Phaser.Types.Core.GameConfig = {
type: Phaser.AUTO,
width: 800,
height: 600,
physics: {
default: "arcade",
arcade: {
gravity: { y: 200 }
}
},
scene: [MyGame]
};
// 启动游戏
new Phaser.Game(config);
总结
TypeScript 的内置函数涵盖了 JavaScript 的所有原生功能,并通过类型系统增强了安全性。主要分为:
JavaScript 原生函数:如 Array.map
、String.trim
、Promise
等。
类型系统函数:如类型断言、泛型、工具类型等。
装饰器与元编程:如类装饰器、方法装饰器。
DOM/Browser API:如 document.querySelector
、fetch
。
游戏开发中,TypeScript 的内置函数和特性主要用于:
数学计算:位置、碰撞检测、随机生成。
实体管理:使用数组方法处理游戏对象集合。
游戏循环:通过定时器和动画帧实现。
类型安全:利用接口、类和泛型构建健壮的游戏架构。
资源管理:异步加载和处理游戏资源。
渲染与交互:结合 DOM 和 Canvas API 实现可视化界面。
cocos creator,laya,egret,phase,threejs,对ts都有良好的支持,如果感兴趣可以去官方获取相关资料进一步学习。