【AICon】AI 基础设施、LLM运维、大模型训练与推理,一场会议,全方位涵盖! >>> 了解详情
写点什么

TypeScript 1.8 新功能:模块扩充

  • 2016-05-25
  • 本文字数:1232 字

    阅读完需:约 4 分钟

TypeScript 是微软开源的一个 JavaScript 的超集。近日,TypeScript 发布了 1.8 稳定版本。

继上个月 Beta 版本发布 之后,微软项目经理 Bowden Kelly 这次在博文 TypeScript 1.8 版本发布 中宣布:基于新增的代码集成功能(在 TypeScript 项目中使用 JavaScript 代码),最新版本现在“完全支持模块扩充了”。

用 Kelly 的话具体来说,这可以“让用户通过模块扩充来设计更加模块化的组件”,帮助他们扩展已有的模块,并在“引入整个模块或部分模块”上自由选择。这可以通过声明引入附加模块来实现,具体的类型扩展工作则在附加模块中完成。

这里是 Kelly 提供的例子:

复制代码
// 基类所在的文件 scale.ts
export class Scale {
weightOnEarth(mass) {}
}
// 附加模块 advancedScale.ts
import { Scale } from "./scale" ;
// 扩充 Scale 类
declare module "./scale" {
// 通过新的接口描述来扩充引入的基类
interface Scale {
weightOnMoon(mass); // 不是所有人都需要月球上的重力
}
}
Scale.prototype.advancedMethod = /* 具体实现略去 */;
// consumer.ts
import { Scale } from "./scale";
import "./advancedScale";
let scale: Scale;
scale.weightOnMoon(10); // 现在可以用了!

去年九月的 1.6 Beta 版本中,微软首次支持了 React。这次,1.8 稳定版本简化了使用 React 时对 props 类型的声明。

简要地说,现在开发者不再需要显式声明 refkey 或者扩展 React.Props 了,refkey 属性可以在所有组件上表现出正确的类型,同时 ref 也会在无状态函数组件中被正确地禁用。

1.8 版本还改善了联合 / 交叉接口。例如,从 string | string[] 推导 string | T 时,后者会被拆解为 string[]T,于是 string[] 就可以推导为 T 了,如下所示:

复制代码
type Maybe<t> = T | void;
function isDefined<t>(x: Maybe<t>): x is T {
return x !== undefined && x !== null;
}
function isUndefined<t>(x: Maybe<t>): x is void {
return x === undefined || x === null;
}
function getOrElse<t>(x: Maybe<t>, defaultValue: T): T {
return isDefined(x) ? x : defaultValue;
}
function test1(x: Maybe<string>) {
let x1 = getOrElse(x, "Undefined"); // 字符串
let x2 = isDefined(x) ? x : "Undefined"; // 字符串
let x3 = isUndefined(x) ? "Undefined" : x; // 字符串
}
function test2(x: Maybe<number>) {
let x1 = getOrElse(x, -1); // 数值
let x2 = isDefined(x) ? x : -1; // 数值
let x3 = isUndefined(x) ? -1 : x; // 数值
}
</number></string></t></t></t></t></t></t></t>

关于 TypeScript 1.8 带来的种种改善与变化的完整细节,敬请参阅它的 GitHub 页面

查看英文原文: TypeScript 1.8 Brings Module Augmentation Support


感谢丁晓昀对本文的审校。

给InfoQ 中文站投稿或者参与内容翻译工作,请邮件至 editors@cn.infoq.com 。也欢迎大家通过新浪微博( @InfoQ @丁晓昀),微信(微信号: InfoQChina )关注我们。

2016-05-25 19:003234

评论

发布
暂无评论
发现更多内容
TypeScript 1.8 新功能:模块扩充_JavaScript_James Chesters_InfoQ精选文章