在 TypeScript 中,使用 map
函数的基本用法与 JavaScript 类似,但是您可以使用类型注解来明确函数的输入和输出类型。以下是一个 TypeScript 中使用 map
函数的示例:
-
翻倍数组中的每个元素:
const numbers: number[] = [1, 2, 3, 4, 5];const doubledNumbers: number[] = numbers.map(function (num: number): number {return num * 2; });console.log(doubledNumbers); // 输出:[2, 4, 6, 8, 10]
或者使用箭头函数和类型推断:
const numbers: number[] = [1, 2, 3, 4, 5];const doubledNumbers: number[] = numbers.map(num => num * 2);console.log(doubledNumbers); // 输出:[2, 4, 6, 8, 10]
-
从对象数组中提取特定属性:
type Student = {name: string;age: number; };const students: Student[] = [{ name: "Alice", age: 25 },{ name: "Bob", age: 30 },{ name: "Charlie", age: 22 }, ];const studentNames: string[] = students.map(function (student: Student): string {return student.name; });console.log(studentNames); // 输出:["Alice", "Bob", "Charlie"]
或者使用箭头函数和类型推断:
type Student = {name: string;age: number; };const students: Student[] = [{ name: "Alice", age: 25 },{ name: "Bob", age: 30 },{ name: "Charlie", age: 22 }, ];const studentNames: string[] = students.map(student => student.name);console.log(studentNames); // 输出:["Alice", "Bob", "Charlie"]