TS3.1
元组和数组上的映射类型
TS3.1在元组和数组上的映射对象类型现在会生成新的元组/数组,而非创建一个新的类型并且这个类型具有push(),pop()和length这样的成员.
type MapToPromis<T> = { [K in keyof T]: Promise<T[K]>};
type Coordinate = [number, number];
type PromiseCoordinate = MapToPromise<Coordinate>;
// [Promise<number>, Promise<number>];
MapToPromise接收参数T,当它是个像Coordinate这样的元组时,只有数值型属性会被转换.[number, number]具有两个数值型属性: 0和1.针对这样的数组,MapToPromise会创建一个新的元组,0和1属性是原类型的一个Promise.因此PromiseCoordinate的类型为[Promise, Promise].
函数上的属性声明
TS3.1提供了在函数声明上定义属性的能力,还支持const声明的函数.只需要在函数直接给属性赋值就可以了.
function readImage(path: string, callback: (err: any, image: Image) => void) { //... }
readImage.sync = (path: string) => {
const contents = fs.readFileSync(path);
return decodeImageSync(contents);
}
readImage函数异步地读取一张图片.此外,还在readImage上提供了一个便捷的函数readImage.sync.
这种属性声明的方式允许我们表达一些常见的模式,例如React无状态函数型组件(SFCs)里的defaultProps和propTpes.
export const FooComponent => ({ name }) => ( <div>Hello! I am { name } </div>);
FooComponent.defaultProps = {
name: "(anonymous)"
}