在这篇文章中,我们将通过Angular中的例子将typecript中的任何类型转换为对象。
本教程包括以下内容
- 如何改变typescript中的变量类型
- 在Angular中转换任何类型为字符串或数字
- 在Angular中解析任何类型为接口或类别
在typescript中,没有类型转换,但我们有类型断言。所以有两种方法可以将任何对象转换为不同的数据类型。
使用通用<>符号
类型断言是告诉编译器一个变量的类型,而不是推断其值。
例如,如果我们声明一个带有数字值的any 类型的变量。
当我们将其分配给另一个变量时,我们告诉编译器并将其解析为数字。
let numb: any = 111;
let id = numb;
console.log(typeof(id)); //Output: number
还有一种方法是使用as关键字
作为关键字
let numb: any = 111;
let id = numb as number;
console.log(typeof(id)); //Output: number
Generics<>在有tsx文件的文件中不起作用,因为关键字是将一种类型转换为另一种类型的首选方式。
如何在typescript中把任何类型转换为字符串?
在下面的例子中,使用typescript中的generics将any类型的变量解析为字符串变量。
display(anyvalue: any) {
this.str = anyvalue;
}
我们也可以使用as关键字,这在typescript中是比较好的。
display(anyvalue: any) {
this.str = anyvalue as string;
}
import { Component, VERSION } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
str = 'hello';
constructor() {
this.display(123);
}
display(anyvalue: any) {
this.str = anyvalue;
}
}
如何将any转为接口或对象转为Angular类(类型)?
有时,API返回任何类型的数据,所以你需要在Angular中转换为接口或类,我们可以用as 关键字和类型断言来完成。
let emp:Employee= anytype as Employee
在typescript中,Employee是一个带有id和name字段的接口。
我们也可以用泛型来做,如下图所示
let emp:Employee= anytype
完整的例子如下
import { Component, VERSION } from '@angular/core';
import { Employee } from '../employee';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
employee: Employee;
constructor() {
this.display({
id: 1,
name: 'john'
});
}
display(anyvalue: any) {
this.employee = anyvalue as Employee;
}
}