typescript赋值
时间: 2023-09-24 17:13:38 浏览: 52
TypeScript是一种静态类型的编程语言,因此在进行赋值操作时需要考虑变量类型的一致性。
1. 基本类型赋值
基本类型包括number、string、boolean等,赋值时需要确保类型一致。
```typescript
let num: number = 123;
let str: string = "hello";
let bool: boolean = true;
```
2. 数组赋值
数组可以使用[]或Array<>的方式定义,赋值时需要确保数组元素类型一致。
```typescript
let arr1: number[] = [1, 2, 3];
let arr2: Array<number> = [1, 2, 3];
let arr3: string[] = ["hello", "world"];
let arr4: Array<string> = ["hello", "world"];
```
3. 对象赋值
对象可以使用{}或interface的方式定义,赋值时需要确保对象属性类型一致。
```typescript
let obj1: {name: string, age: number} = {name: "Tom", age: 18};
interface Person {
name: string;
age: number;
}
let obj2: Person = {name: "Tom", age: 18};
```
4. 函数赋值
函数可以使用() => {}或function的方式定义,赋值时需要确保函数参数类型和返回值类型一致。
```typescript
let fn1: (x: number, y: number) => number = function(x: number, y: number): number {return x + y};
function fn2(x: number, y: number): number {return x + y};
let fn3: (x: string, y: string) => string = function(x: string, y: string): string {return x + y};
function fn4(x: string, y: string): string {return x + y};
```
5. 类赋值
类可以使用class关键字定义,赋值时需要使用new关键字创建实例。
```typescript
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
sayHello() {
console.log(`Hello, I'm ${this.name}.`);
}
}
let dog: Animal = new Animal("Dog");
dog.sayHello();
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)