TypeScript的Dictionary的写法

TypeScript中做类似ActionScript中的Dictionary功能时的写法

var dict: { [index: string]: Function[]; } = {};
dict['Matt'] = []; // ok
dict['Chris'] ="123"; //编译警告
dict[1] =  []; //编译警告

还有一种方法就是使用typescript-collections 里面的Dictionary类

https://github.com/basarat/typescript-collections#a-sample-on-dictionary

用法是这样的。

class Person {
    constructor(public name: string, public yearOfBirth: number,public city?:string) {
    }
    toString() {
        return this.name + "-" + this.yearOfBirth; // City is not a part of the key. 
    }
}

class Car {
    constructor(public company: string, public type: string, public year: number) {
    }
    toString() {
        // Short hand. Adds each own property 
        return collections.toString(this);
    }
}
var dict = new collections.Dictionary<Person, Car>();
dict.setValue(new Person("john", 1970,"melbourne"), new Car("honda", "city", 2002));
dict.setValue(new Person("gavin", 1984), new Car("ferrari", "F50", 2006));
console.log("Orig");
console.log(dict);

// Changes the same john, since city is not part of key 
dict.setValue(new Person("john", 1970, "sydney"), new Car("honda", "accord", 2006)); 
// Add a new john
dict.setValue(new Person("john", 1971), new Car("nissan", "micra", 2010)); 
console.log("Updated");
console.log(dict);

// Showing getting / setting a single car: 
console.log("Single Item");
var person = new Person("john", 1970); 
console.log("-Person:");
console.log(person);

var car = dict.getValue(person);
console.log("-Car:");
console.log(car.toString());

 

转载于:https://www.cnblogs.com/longhuang/p/3645555.html

### TypeScript 编程语法概述 TypeScript 是一种由微软开发的自由和开源编程语言,它作为 JavaScript 的超集,在其基础上增加了可选的静态类型和其他面向对象编程特性[^2]。 #### 基础数据类型的定义 在 TypeScript 中,可以通过显式声明变量的数据类型来增强代码的安全性和可读性: ```typescript let isDone: boolean = false; let age: number = 27; let name: string = "Alice"; ``` #### 函数及其参数与返回值类型标注 为了提高程序健壮性并减少运行时错误的发生率,可以在函数签名处指定输入参数以及预期输出的结果类型。下面是一个简单的加法运算例子[^3]: ```typescript function add(x: number, y: number): number { return x + y; } console.log(add(5, 10)); // 输出:15 ``` #### 使用 `never` 类型处理异常情况 当某个表达式的执行路径总是会提前终止(如抛出错误),则该位置应被标记为 `never` 类型。这有助于编译器识别潜在逻辑漏洞,并提醒开发者注意边界条件[^4]: ```typescript function throwError(message: string): never { throw new Error(message); } try { let message: string = 'Hello, TypeScript!'; if (typeof message !== 'string') { throwError('Expected a string'); } console.log(message); } catch(e) { console.error(e.message); } ``` 通过上述几个方面的介绍可以看出,TypeScript 不仅继承了 JavaScript 所有的功能特点,还引入了许多现代化的语言特性和工具支持,使得大型应用系统的构建变得更加容易维护和发展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值