接下来我们在 TypeScript 文件 type.ts 中创建一个简单的 area() 函数: functionarea(shape:string,width:number,height:number){vararea=width*height;return"I'm a "+shape+" with an area of "+area+" cm squared.";}document.body.innerHTML=area("rectangle",30,15); 接下来,修改index.html的 js ...
functionsum(numbers:number[]):number{returnnumbers.reduce((acc,num)=>acc+num,0);}console.log(sum([1,2,3,4,5]));// 输出: 15 1. 2. 3. 4. 元组参数示例 functiondisplayPerson(person:[string,number]):string{return`Name:${person[0]}, Age:${person[1]}`;}console.log(displayPerson(...
同样,在TypeScript 中也支持这样的参数类型定义,如下代码所示:function sum(...nums: number[]) {return nums.reduce((a, b) => a + b, 0);}sum(1, 2); // => 3sum(1, 2, 3); // => 6sum(1, '2'); // ts(2345) Argument of type 'string' is not assignable to parameter of ...
functiont(name:string){return`hello,${name}`;}t("lucifer"); 字符串 "lucifer" 是 string「类型」的一个具体「值」。在这里 "lucifer" 就是值,而 string 就是类型。 TS 明白 "lucifer" 是 string 集合中的一个元素,因此上面代码不会有问题,但是如果是这样就会报错: 代码语言:javascript 代码运行次数:0...
function add(x: number, y: number): number { return x + y; } let myAdd = function(x: number, y: number): number { return x + y; }; 1. 2. 3. 4. 5. 2,可选参数和默认参数: TypeScript里的每个函数参数都是必须的。 这不是指不能传递 null或undefined作为参数,而是说编译器检查用户...
Typing the function 2.1.2. Writing the function type 2.1.3. Optional and Default Parameters 2.1.4. Rest Parameters 2.1.5. Overloads 2.2. Unions and Intersection Types 2.2.1. Union Types 2.3. Conditional Types 2.4. Type inference in conditional types 3. useReducer 定义解析 本系列文章将从一些...
function identity<T>(arg: T): T { return arg;}在函数名之后,我们在尖括号<>中加了了一个类型变量T。T现在是我们想传递给identity的类型的占位符,并被分配给arg来代替它的类型:T现在代替number充当类型。 注意:类型变量也称为类型参数和泛型参数。本文选择使用术语“类型变量”,与官方TS文档一致。
function add(n:number,m:number){console.log(n+m)}add(10,20);add(10,"20"); // Argument of type 'string' is not assignable to parameter of type 'number' TypeScript与JavaScript的关系 为了更好的理解,我们可以将三者看成是包含关系
functionarea(shape:string,width:number,height:number){vararea=width*height;return"I'm a "+shape+" with an area of "+area+" cm squared.";}document.body.innerHTML=area("rectangle",30,15); 接下来,修改index.html的 js 文件为type.js然后编译 TypeScript 文件:tsc type.ts。
enumA{x='x',y='y',z='z',}enumB{x='x',y='y',z='z',}function fn(val:A){}fn(B.x);//TS2345:Argument of type'B.x'isnotassignable to parameter of type'A'.; 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12.