浅谈 TypeScript 特性 (二)

来源:互联网 发布:游戏编程教学 编辑:程序博客网 时间:2024/06/07 20:06

浅谈 TypeScript 特性

*  类型推论

1. 如果没有声明类型 typescript 会推论出一个通用类型, 如下 a 会被推论出为 string[] 

const a = [1,2,3]
const a2 =a[0];
2. 如果表达式是如下, 是会报错的, 因为此时没有找到最佳通用类型, 类型的推论的结果将是空对象{}  故访问其成员会报错
const c = [{a:1}, {b:2}, {c: "3"}];
const c2 =c[0].a;// error
此时需要手动声明
interface arrayc {
[key: string]:number |string;
}
const c:arrayc[] = [{a:1}, {b:2}, {c: "3"}];
const c2 =c[0].a;// ok

*  类型兼容性
如下 x=y 成功 但是x不能访问location属性, y =x错误, 因为Named不是y的类型
interface Named {
name: string;
}
let x: Named;
// y's inferred type is { name: string; location: string; }
let y = { name: 'Alice', location: 'Seattle' };
x= y;
x.location;// [ts] Property 'location' does not exist on type 'Named'
y=x;// [ts]Type 'Named' is not assignable to type '{ name: string; location: string; }'.
*  交叉类型
返回一个你需要的兼容两个对象的子对象
如下 <any>result[id] 的写法 如果 T, U 有一样的属性, 但是类型不一样 直接写 resule[id] 会报错, 故需用类型断言来约束 
function extend<T,U>(first:T, second: U): T & U {
let result =<T &U>{};
for (letidin first) {
(<any>result)[id] =first[id];
}
for (letidin second) {
if (!result.hasOwnProperty(id)) {
(<any>result)[id] =second[id];
}
}
return result;
}

class Person {
constructor(publicname:string) { }
}
interface Loggable {
log(): void;
}
class ConsoleLoggerimplementsLoggable {
log() {
// ...
}
}
var jim =extend(newPerson("Jim"),new ConsoleLogger());
* 类型保护
有时候你需要如下的判断, 均会报错。因为 pet.swim 不一定存在pet中。
interface swim {
swim: ()=> {}
}
interfacefly{
fly: ()=>{}
}
letpet: swim |fly;
if (pet.swim) {
pet.swim();
}
elseif (pet.fly) {
pet.fly();
}
此时需要类型断言, <swim>pet 会先把pet定为为swim类型, 然后才能去去判断是否存在
interface swim {
swim: ()=> {}
}
interface fly{
fly: ()=>{}
}
let pet: swim | fly;
if ((<swim>pet).swim) {
(<swim>pet).swim();
}
else if ((<fly>pet).fly) {
(<fly>pet).fly();
}
* 类型谓词与用户自定义类型保护
function isFish(pet:swim |fly):pet is swim {
return (<swim>pet).swim !==undefined;
}
以后只需调用isFish()即可, 显然如下的方式是最佳的
// 注意TypeScript不仅知道在if分支里pet是swim类型; 它还清楚在 else分支里,一定不是swim类型,一定是fly类型。
if (isFish(pet)) {
pet.swim();
}
else {
pet.fly();
}
* 索引类型
1. keyof 操作符返回对象key类型
functionpluck<T, K extends keyofT>(o: T, names: K[]):T[K][] {
returnnames.map(n=> o[n]);
}
interfacePerson {
name:string;
age:number;
}
letperson: Person = {
name:'Jarid',
age:35
};
letstrings: string[] =pluck(person, ['name']);// ok, string[]
2. keyof使用
let a:keyof {name: "Sss",sex : "women"}
a="name"// ok
a="sex"//ok
a= "hello word"// error

原创粉丝点击