TypeScript in 5 minutes
https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html
Let’s get started by building a simple web application with TypeScript.
Installing TypeScript #
There are two main ways to get the TypeScript tools:
- Via npm (the Node.js package manager)
- By installing TypeScript’s Visual Studio plugins
Visual Studio 2017 and Visual Studio 2015 Update 3 include TypeScript by default. If you didn’t install TypeScript with Visual Studio, you can still download it.
For NPM users:
> npm install -g typescript
npm 安装的路径在 C:\Users\clu\AppData\Roaming\npm\node_modules\typescript\bin
Building your first TypeScript file #
In your editor, type the following JavaScript code in greeter.ts
:
function greeter(person) {
return "Hello, " + person;
} let user = "Jane User"; document.body.textContent = greeter(user);
Compiling your code #
We used a .ts
extension, but this code is just JavaScript. You could have copy/pasted this straight out of an existing JavaScript app.
At the command line, run the TypeScript compiler:
tsc greeter.ts
The result will be a file greeter.js
which contains the same JavaScript that you fed in. We’re up and running using TypeScript in our JavaScript app!
Now we can start taking advantage of some of the new tools TypeScript offers. Add a : string
type annotation to the ‘person’ function argument as shown here:
function greeter(person: string) {
return "Hello, " + person;
}
let user = "Jane User";
document.body.textContent = greeter(user);
Type annotations #
Type annotations in TypeScript are lightweight ways to record the intended contract of the function or variable.
In this case, we intend the greeter function to be called with a single string parameter.
We can try changing the call greeter to pass an array instead:
function greeter(person: string) {
return "Hello, " + person;
} let user = [0, 1, 2]; document.body.textContent = greeter(user);
Re-compiling, you’ll now see an error:
error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'string'.
Similarly, try removing all the arguments to the greeter call. TypeScript will let you know that you have called this function with an unexpected number of parameters. In both cases, TypeScript can offer static analysis based on both the structure of your code, and the type annotations you provide.
Notice that although there were errors, the greeter.js
file is still created. You can use TypeScript even if there are errors in your code. But in this case, TypeScript is warning that your code will likely not run as expected.
Interfaces #
Let’s develop our sample further. Here we use an interface that describes objects that have a firstName and lastName field.
In TypeScript, two types are compatible if their internal structure is compatible.
This allows us to implement an interface just by having the shape the interface requires, without an explicit implements
clause.
interface Person {
firstName: string;
lastName: string;
} function greeter(person: Person) {
return "Hello, " + person.firstName + " " + person.lastName;
} let user = { firstName: "Jane", lastName: "User" }; document.body.textContent = greeter(user);
Classes #
Finally, let’s extend the example one last time with classes. TypeScript supports new features in JavaScript, like support for class-based object-oriented programming.
Here we’re going to create a Student
class with a constructor and a few public fields. Notice that classes and interfaces play well together, letting the programmer decide on the right level of abstraction.
Also of note, the use of public
on arguments to the constructor is a shorthand that allows us to automatically create properties with that name.
class Student {
fullName: string;
constructor(public firstName: string, public middleInitial: string, public lastName: string) {
this.fullName = firstName + " " + middleInitial + " " + lastName;
}
} interface Person {
firstName: string;
lastName: string;
} function greeter(person: Person) {
return "Hello, " + person.firstName + " " + person.lastName;
} let user = new Student("Jane", "M.", "User"); document.body.textContent = greeter(user);
Re-run tsc greeter.ts
and you’ll see the generated JavaScript is the same as the earlier code.
Classes in TypeScript are just a shorthand for the same prototype-based OO that is frequently used in JavaScript.
Running your TypeScript web app #
Now type the following in greeter.html
:
<!DOCTYPE html>
<html>
<head><title>TypeScript Greeter</title></head>
<body>
<script src="greeter.js"></script>
</body>
</html>
Open greeter.html
in the browser to run your first simple TypeScript web application!
Optional: Open greeter.ts
in Visual Studio, or copy the code into the TypeScript playground. You can hover over identifiers to see their types. Notice that in some cases these types are inferred automatically for you. Re-type the last line, and see completion lists and parameter help based on the types of the DOM elements. Put your cursor on the reference to the greeter function, and hit F12 to go to its definition. Notice, too, that you can right-click on a symbol and use refactoring to rename it.
The type information provided works together with the tools to work with JavaScript at application scale. For more examples of what’s possible in TypeScript, see the Samples section of the website.
TypeScript in 5 minutes的更多相关文章
- 中文代码示例之5分钟入门TypeScript
"中文编程"知乎专栏原文 Typescript官方文档起的这个噱头名字: TypeScript in 5 minutes, 虽然光看完文章就不止5分钟...走完整个文档流水账如下( ...
- 2018-05-09 5分钟入门CTS-尝鲜中文版TypeScript
知乎原链 本文为中文代码示例之5分钟入门TypeScript的CTS版本. CTS作者是@htwx(github). 它实现了关键词和标准库的所有命名汉化. 本文并未使用附带的vscode相关插件(包 ...
- AngularJS 2 Typescript 相关
1. Angular 2 In 60 Minutes (2016年11月23日) https://www.youtube.com/watch?v=-zW1zHqsdyc 2. AngularJS Cl ...
- 0前端 框架 库_千万别去碰js呀 混合APP_webAPP_美工 选有类型的语言,比如TypeScript
常用知识点,技巧 添加库到本地: (举例 element-ui) 用npm命令行把包下载到本地 在电脑里找到资源文件,比如 C:\Users\XiaoCong\AppData\Roaming\npm\ ...
- 在 Vue 中使用 Typescript
前言 恕我直言,用 Typescript 写 Vue 真的很难受,Vue 对 ts 的支持一般,如非万不得已还是别在 Vue 里边用吧,不过听说 Vue3 会增强对 ts 的支持,正式登场之前还是期待 ...
- 使用 Yarn workspace,TypeScript,esbuild,React 和 Express 构建 K8S 云原生应用(一)
本文将指导您使用 K8S ,Docker,Yarn workspace ,TypeScript,esbuild,Express 和 React 来设置构建一个基本的云原生 Web 应用程序. 在本教程 ...
- TypeScript: Angular 2 的秘密武器(译)
本文整理自Dan Wahlin在ng-conf上的talk.原视频地址: https://www.youtube.com/watch?v=e3djIqAGqZo 开场白 开场白主要分为三部分: 感谢了 ...
- TypeScript为Zepto编写LazyLoad插件
平时项目中使用的全部是jQuery框架,但是对于做webapp来说jQuery太过于庞大,当然你可以选择jQuery 2.*针对移动端的版本. 这里我采用移动端使用率比较多的zepto框架,他跟jqu ...
- TypeScript Vs2013 下提示Can not compile modules unless '--module' flag is provided
VS在开发TypeScript程序时候,如果import了模块有的时候会有如下提示: 这种情况下,只需要对当前TypeScript项目生成设置为AMD规范即可!
随机推荐
- main process exited, code=exited, status=203/EXEC
问题描述: Oct :: c_3. systemd[]: Started etcd. Oct :: c_3. systemd[]: Starting etcd... Oct :: c_3. syste ...
- SpringBoot + Nginx 配置HTTPS的一次经历
最近公司开发了一款小程序的应用,但是小程序为了保证数据安全,强制要求使用HTTPS,然后就不得不去配置了一下. 之前在php开发的项目上配置过一次,使用的是wdcp的控制台程序,配置起来很简单,不需要 ...
- Copy Files from Windows 10 to wsl
Method 1 reboot( close wsl window and reopen ) Method 2 – Windows System Drive as a Mount point Wind ...
- python中#!含义
LINUX 上的 Shebang 符号(#!) #!这个符号叫做 Shebang 或者 Sha-bangShebang 通常在 Unix 系统脚本的中第一行开头使用指明执行这个脚本文件的解释程序 使用 ...
- 【使用DIV+CSS重写网站首页案例】CSS浮动
CSS浮动: 浮动的框可以向左或向右移动,直到它的外边缘碰到包含框或另一个浮动框的边缘为止 由于浮动框不在文件的普通流中,所以文档的普通流中的块框表现得就像浮动框不存在一样. 选择器之 float属性 ...
- 多态典型用例之virtual
多态典型用例之virtual 参考:https://www.cnblogs.com/dormant/p/5223215.html 1.虚函数(virtual) (1)在某基类中声明为 virtual ...
- Python 基础-> 字符串,数字,变量
Python 基础:字符串,数字,变量 1. 字符串 (信息的一种表达方式) a. 使用引号创建字符串 b. 单引号,双引号,三引号: ', ", ''', ""&quo ...
- driver.implicitly_wait()与time.sleep()的区别
implicitly_wait(5)属于隐式等待,5秒钟内只要找到了元素就开始执行,5秒钟后未找到,就超时: time.sleep(5)表示必须等待5秒定位: 如何灵活运用这两种方式: 当某个页面元素 ...
- 转载 Easyui Tree方法扩展 - getLevel(获取节点级别)
Easyui Tree一直就没有提供这个方法,以前没有用到,所 以一直没怎么在意,这次自己用到了,顺便扩展了一个方法,分享给大家. $.extend($.fn.tree.methods, { getL ...
- wordpress调用文章摘要,若无摘要则自动截取文章内容字数做为摘要
以下是调用指定分类文章列表的一个方法,作者如果有填写文章摘要则直接调用摘要:如果文章摘要忘记写了则自动截取文章内容字数做为摘要.这个方法也适用于调用description标签 <ul> & ...