概述
说明
TypeScript 是 JavaScript 的超集
安装
npm install -g typescript
tsc -v
运行
tsc test.ts test01.ts test02.ts
node test.js
组成
- 模块
- 函数
- 变量
- 语句和表达式
- 注释
基础类型
- any (任意)
- nunber (数字)
- string (字符串)
- boolean (布尔)
- 数组
- 元组
- enum (枚举)
- void
- null 表示对象值缺失
- undefined 用于初始化变量为一个未定义的值
- never 是其它类型的子类型,代表从不出现的值
let uname:string = "Cyan"
let years:number = 5
let flag:boolean = true
let arr1:number[] = [1, 2]
let arr2:Array<number> = [1, 2]
// 元组用来表示已经元素数量和类型的数组
let x:[string, number]
x = ['Cyan', 1]
// 枚举用于定义数值集合
enum Color {Red, Green, Blue}
let c: Color = Color.Blue
// void用于标识方法返回值的类型,表示该方法没有返回值
function hello(): void {
alert('x')
}
变量声明
var uname:string = "Cyan"
var score:number = 50
运算符
- 算术运算符
- 逻辑运算符
- 关系运算符
- 按位运算符
- 赋值运算符
- 三元/条件运算符
- 字符串运算符
- 类型运算符
var num = 12
console.log(typeof num)
条件语句
var num:number = 5
if (num > 10) {
console.log('xxx')
}else if(num > 0){
console.log('yyy')
}else{
console.log('zzz')
}
switch(num) {
case 1: {
console.log(1)
break;
}
case 5: {
console.log(2)
break;
}
default: {
console.log(3);
break;
}
}
循环
var num:number = 5
var i:number
var factorial = 1
for(i = num;i >= 1;i--){
factorial *= i;
}
console.log(factorial)
var j:any
var n:any = "a b c"
for(j in n){
console.log(n[j])
}
// for of, forEach, every, some
let someArray = [1, "string", false]
for(let entry of someArray){
console.log(entry)
}
var num:number = 5
var factorial:number = 1
while(num >= 1){
factorial = factorial * num
num--
}
console.log(factorial)
// do while, break, continue
函数
function greet():string {
return "Hello World"
}
var msg = greet()
console.log(msg)
// 带参数函数
function add(x:number, y:number):number {
return x + y;
}
console.log(add(1,2))
// 可选参数
function buildName(firstName: string, lastName?: string) {
if(lastName == undefined){
return firstName
}else{
return firstName + " " + lastName
}
}
console.log(buildName("Cyan"))
console.log(buildName("Cyan", "Hu"))
// 默认参数
function calculate_discount(price:number, rate:number = 0.5) {
var discount = price * rate
console.log("sum:", discount)
}
calculate_discount(1000)
calculate_discount(1000, 0.3)
// 剩余参数
function addNumbers(...nums:number[]){
var i
var sum:number = 0;
for(i = 0;i<nums.length;i++){
sum += nums[i]
}
console.log("sum is",sum)
}
addNumbers(1,2,3,4,5)
// 匿名函数
var res = function(a:number, b:number) {
return a*b
}
console.log(res(15, 7))
// 匿名函数自调用
;(function(){
var x = 'Hello!!!'
console.log(x)
})()
// 构造函数
var myFunction = new Function("a","b","return a*b")
console.log(myFunction(5,6))
// 递归函数
function factorial(number){
if(number <= 0){
return 1;
} else {
return (number * factorial(number - 1))
}
}
console.log(factorial(6))
// Lambda函数(箭头函数)
var foo = (x:number) => 10 + x
console.log(foo(100))
var func = x => {
if (typeof x == "number"){
console.log(x,"is number")
}else if(typeof x == "string"){
console.log(x,"is string")
}
}
func(10)
func("cyan")
var disp = () => {
console.log('xxx')
}
disp()
// 函数重载
function disx(s1:string):void
function disx(n1:number,s1:string):void
function disx(x:any,y?:any):void {
console.log(x,y)
}
disx("abc")
disx(1,"xyz")
Number
Number 对象是原始数值的包装对象。
// Number对象的属性
console.log("max is", Number.MAX_VALUE)
console.log("min is", Number.MIN_VALUE)
console.log("负无穷", Number.NEGATIVE_INFINITY)
console.log("正无穷", Number.POSITIVE_INFINITY)
console.log("Number函数的引用", Number.constructor)
console.log(Number.NaN)
// prototype
function employee(id:number, name:string){
this.id = id
this.name = name
}
var emp = new employee(123,"cyan")
employee.prototype.email = "498107319@qq.com"
console.log("id is", emp.id)
console.log("name is", emp.name)
console.log("email is", emp.email)
// Number对象的方法
// toExponential() 转换成指数计数法
var num = new Number(177.12345)
console.log(num.toExponential())
// toFixed() 转换为字符串,并保存几位小数
console.log(num.toFixed(2))
// toLocaleString() 数字转字符串,使用本地数字格式顺序
console.log(num.toLocaleString())
// toPrecision() 数字格式化为指定的长度
console.log(num.toPrecision())
console.log(num.toPrecision(1))
console.log(num.toPrecision(2))
// toString 数字转为字符串,使用指定的基数。范围2-36之间的整数,默认是10
console.log(num.toString(2)) //转2进制
console.log(num.toString(8)) //转8进制
console.log(num.toString(16)) //转16进制
// valueOf() 返回一个Number对象的原始数字值
console.log(num.valueOf())
String
var str = new String("This is string");
// String对象的属性
// constructor 对创建该对象的函数的引用
console.log(str.constructor)
// length 长度
console.log('length:',str.length)
// prototype 向对象添加属性和方法
function employee(id:number, name:string){
this.id = id
this.name = name
}
var emp = new employee(123, "cyan")
employee.prototype.email = '498107319@qq.com'
console.log('id', emp.id)
console.log('name', emp.name)
console.log('email', emp.email)
// String对象的方法
// charAt() 返回指定位置的字符
var str = new String("CYANHU")
console.log(str.charAt(1))
// charCodeAt() 返回指定位置字符的Unicode编码
console.log(str.charCodeAt(1))
// concat() 连接两个或以上字符串,并返回新的
console.log(str.concat( " say:Hello!" ))
// indexOf() 返回指定的字符串值在字符串中首次出的位置
console.log(str.indexOf("H"))
// lastIndexOf() 从后向前搜索字符串,返回指定字符串在字符串中最后出次的位置
console.log(str.lastIndexOf("Y"))
// localeCompare() 用本地特定的顺序来比较两个字符串
console.log(str.localeCompare("CYANHU"))
// match() 查找找到一个或多个正则表达式的匹配
var str1 = "The rain in SPAIN stays mainly in the Plain"
var n = str1.match(/ain/g)
// replace() 替换与正则表达式匹配的子串
var re = /(w+)s(w+)/;
var str2 = "zara ali";
console.log(str2.replace(re,"$2,$1"))
// search() 检索与正则表达式相匹配的值
var re = /apples/gi
var str3 = "Apples are round, and apples are juicy."
if(str3.search(re) === -1){
console.log('Does not contain Apples')
}else{
console.log('Contains Apples')
}
// slice() 提取字符串的片断,并在新的字符串中返回被提取的部分
// split() 把字符串分割为子字符串数组
console.log(str3.split(" ",3))
// substr() 从起始索引号提取字符串中指定数目的字符
// substring() 提取字符串中两个指定的索引号之间的字符
console.log(str3.substring(1,5))
// toLocaleLowerCase() 根据主机的语言环境把字符串转换为小写,只有几种语言具有地方特有的大不写映射
console.log(str.toLocaleLowerCase())
// toLocaleUpperCase() 根据主机的语言环境把字符串转换为大写,只有几种语言具有地方特有的大不写映射
console.log(str3.toLocaleUpperCase())
// toLowerCase() 把字符串转换为小写
console.log(str.toLowerCase())
// toUpperCase() 把字符串转换为大写
console.log(str3.toUpperCase())
// toString() 返回字符串
console.log(str.toString())
// valueOf() 返回指定字符串对象的原始值
console.log(str.valueOf())
Array
// 声明和初始化
var sites:string[]
sites = ["Google", "Baidu", "Taobao"]
var numlist:number[] = [2, 4, 6, 8]
console.log(sites[0])
console.log(numlist[1])
// Array对象
var arr_names:number[] = new Array(4)
for(var i=0;i<arr_names.length;i++){
arr_names[i] = i * 2
}
console.log(arr_names)
// 数组解构
var arr:number[] = [12, 13]
var[x, y] = arr
console.log(x,y)
// 数组迭代
var j:any
var nums:number[] = [1001, 1002, 1003, 1004]
for(j in nums){
console.log(nums[j])
}
// 多维数组
var multi:number[][] = [[1,2,3],[23,24,25]]
console.log(multi[1][2])
// 数组在函数中的使用
// 作为参数传递给函数
var sites:string[] = new Array("Google","Baidu","Taobao","Facebook")
function disp1(arr_sites:string[]){
for(var i=0;i<arr_sites.length;i++){
console.log(arr_sites[i])
}
}
disp1(sites)
// 作为函数的返回值
function disp2():string[] {
return new Array("Google","Baidu","Taobao","Facebook")
}
var sites = disp2()
var j:any
for(j in sites){
console.log(sites[j])
}
// 数组方法
// concat() 连接两个或更多的数组,并返回结果
var alpha = ["a", "b", "c"]
var numeric = ["1", "2", "3"]
var alphaNumeric = alpha.concat(numeric)
console.log(alphaNumeric)
// every() 检测数值元素的每个元素是否都符合条件
function isBigEnough(element, index, array){
return (element >= 10)
}
var passed1 = [12,5,8,130,44].every(isBigEnough)
console.log(passed1)
// filter() 检测数值元素,并返回符合条件所有元素的数组
var passed2 = [12,5,8,130,44].filter(isBigEnough)
console.log(passed2)
// forEach() 数组每个元素都执行一次回调函数
let num = [7,8,9]
num.forEach(v=>console.log(v))
// indexOf() 搜索数组中元素,并返回它所在的位置
console.log([12,5,8,130,44].indexOf(8))
// join() 把数组的所有元素放入一个字符串
var arr1 =
new Array("First", "Second", "Third")
console.log(arr1.join(","))
// lastIndexOf() 返回一个指定的字符串值最后出现的位置,从后向前搜索
console.log([12,5,8,130,44].lastIndexOf(8))
// map() 通过指定函数处理数组的每个元素,并返回处理后的数组
var numbers = [1,4,9]
console.log(numbers.map(Math.sqrt))
// pop() 删除最后一个元素,并返回
console.log(numbers.pop())
// push() 向数组的未尾添加一个或更多元素,并返回新的长度
console.log(numbers.push(10))
// reduce() 将数组元素计算为一个值(从左到右)
var total = [0,1,2,3,4].reduce((a,b)=>a+b)
console.log(total)
// reduceRight() 将数组元素计算为一个值(从右到左)
var total1 = [0,1,2,3,4,5].reduceRight((a,b)=>a+b)
// reverse() 反转数组的元素顺序
var arr2 = [0,1,2,3,4].reverse()
console.log(arr2)
// shift() 删除并返回数组的第一个元素
var arr3 = [10,1,2,3,4].shift()
console.log(arr3)
// slice() 选取数组的一部分,并返回一个新数组
var arr4 = ["orange","mango","banana","sugar","tea"]
console.log(arr4.slice(1,2))
console.log(arr4.slice(1,3))
// some() 检测数组元素中是否有元素符合指定条件
console.log([2,5,8,1,4].some(isBigEnough))
// sort() 对数组的元素进行排序
console.log(arr4.sort())
// splice() 从数组中添加或删除元素
var removed = arr4.splice(2,0,"water");
console.log(arr4)
console.log(removed)
// toString() 把数组转换为字符串,并返回结果
console.log(arr4.toString())
// unshift() 向数组的开头添加一个或更多的元素,并返回新的长度
console.log(arr4.unshift("hot water"))
元组
数组中元素数据类型一般都是相同的(any[]类型的数组可以不同),如果存储的元素数据类型不同,则需要使用元组
var mytuple1 = [10,"cyan"]
var mytuple2 = []
mytuple2[0] = 120
mytuple2[1] = 234
// 元组运算
var mytuple3 = [10,"Hello","World","typeScript"]
console.log(mytuple3.length)
mytuple3.push(12)
console.log(mytuple3.length)
mytuple3.pop()
console.log(mytuple3.length)
// 更新元组
mytuple3[0] = 121
console.log(mytuple3)
// 解构元组
var a = [10,"Cyan"]
var [b,c] = a
console.log(b)
console.log(c)
联合类型
可以通过管着(|)将变量设置多种类型,赋值时可以根据设置的类型来赋值
var val:string|number
val = 12
console.log(val)
val = "cyan"
console.log(val)
// 也可以将联合类型作为函数参数使用
function disp(name:string|string[]):void{
if(typeof name == "string"){
console.log(name)
}else{
var i
for(i=0;i<name.length;i++){
console.log(name[i])
}
}
}
disp("Cyan")
disp(["Cyan","Google","Taobao","Facebook"])
//联合类型数组
var arr:number[]|string[];
var i:number
arr = [1,2,4]
for(i=0;i<arr.length;i++){
console.log(arr[i])
}
arr = ["Cyan","Google","Taobao","Facebook"]
for(i=0;i<arr.length;i++){
console.log(arr[i])
}
接口
接口是一系列抽象方法的声明,是一些方法特征的集合,这些方法都应该是抽象的,需要由具体的类去实现,然后第三方就可以通过这组抽象方法调用,让具体的类执行具体的方法。
注意:接口不能转换成JavaScript,它只是TypeScript的一部分
Typescript允许接口继承多个接口
interface IPerson {
firstName:string,
lastName:string,
sayHi:()=>string
}
var customer:IPerson = {
firstName:"Tom",
lastName:"Hanks",
sayHi:():string=>{
return "Hi there"
}
}
console.log(customer.firstName)
console.log(customer.lastName)
console.log(customer.sayHi())
var employee:IPerson = {
firstName:"Jim",
lastName:"Blakes",
sayHi:():string =>{
return "Hello!!!"
}
}
console.log(employee.firstName)
console.log(employee.lastName)
console.log(employee.sayHi())
// 联合类型和接口
interface RunOptions {
program:string,
commandline:string[]|string|(()=>string)
}
var options:RunOptions = {program:"test1",commandline:"Hello"};
console.log(options.commandline)
options = {program:"test1",commandline:["Hello","World"]}
console.log(options.commandline[0])
console.log(options.commandline[1])
options = {program:"test1",commandline:()=>{return "**Hello World**"}}
var fn:any = options.commandline
console.log(fn())
// 接口和数组
interface namelist {
[index:number]:string
}
var list2:namelist = ["John", "Bran"]
interface ages {
[index:string]:number
}
var agelist:ages = {"john":15}
console.log(agelist)
// 接口继承
// 单继承
interface Person {
age:number
}
interface Musician extends Person {
instrument:string
}
var drummer = <Musician>{};
drummer.age = 27
drummer.instrument = "Drums"
console.log(drummer.age)
console.log(drummer.instrument)
// 多继承
interface IParent1 {
v1:number
}
interface IParent2 {
v2:number
}
interface Child extends IParent1,IParent2 {}
var Iobj:Child = {v1:12, v2:23}
console.log(Iobj.v1,Iobj.v2)
类
不支持继承多个类,但支持多重继承
class Car {
engine:string
constructor(engine:string){
this.engine = engine
}
disp():void{
console.log(this.engine)
}
}
var obj = new Car("XXSY1")
console.log(obj.engine)
obj.disp()
// 类的继承
class Shape {
Area:number
constructor(a:number){
this.Area = a
}
}
class Circle extends Shape {
disp():void {
console.log(this.Area)
}
}
var obj1 = new Circle(223)
obj1.disp()
// 多重继承
class Root {
str:string
}
class Child extends Root{}
class Leaf extends Child{}
var obj2 = new Leaf()
obj2.str = "Hello"
console.log(obj2.str)
// 继承类的方法重写
class PrinterClass {
doPrint():void {
console.log("父类的doPrint()方法。")
}
}
class StringPrinter extends PrinterClass {
doPrint():void {
super.doPrint()
console.log("子类的doPrint()方法。")
}
}
// static关键字
class StaticMem {
static num:number
static disp():void {
console.log("num is",StaticMem.num)
}
}
StaticMem.num = 12
StaticMem.disp()
// instanceof运算符 用来判断对象是否是指定的类型
class Person{}
var obj3 = new Person()
var isPerson = obj3 instanceof Person
console.log(isPerson)
// private protected public
class Encapsulate {
str1:string = "hello"
private str2:string = "world"
}
var obj4 = new Encapsulate()
console.log(obj4.str1)
// 类和接口
interface ILoan {
interest:number
}
class AgriLoan implements ILoan {
interest:number
rebate:number
constructor(interest:number,rebate:number){
this.interest = interest
this.rebate = rebate
}
}
var obj5 = new AgriLoan(10, 1)
console.log(obj5.interest,obj5.rebate)
对象
对象是包含一组键值对的实例。 值可以是标量、函数、数组、对象等
var sites = {
site1:"Baidu",
site2:"Google",
sayHello:function(){}
}
console.log(sites.site1)
console.log(sites.site2)
sites.sayHello = function(){
console.log(sites.site1)
}
sites.sayHello();
// 对象也可以作为一个参数传递给函数
var invokesites = function(obj:{site1:string,site2:string}){
console.log(obj.site1)
console.log(obj.site2)
}
invokesites(sites)
// 鸭子类型
interface Ipoint {
x:number,
y:number
}
function addPoints(p1:Ipoint,p2:Ipoint):Ipoint {
var x = p1.x + p2.x
var y = p1.y + p2.y
return {x,y}
}
var newPoint = addPoints({x:3,y:4},{x:5,y:1})
console.log(newPoint)
命名空间
IShape.ts
namespace Drawing {
export interface IShape {
draw();
}
}
Circle.ts
/// <reference path="IShape.ts" />
namespace Drawing {
export class Circle implements IShape {
public draw() {
console.log("Circle is drawn")
}
}
}
Triangle.ts
/// <reference path="IShape.ts" />
namespace Drawing{
export class Triangle implements IShape {
public draw() {
console.log("Triangle is drawn")
}
}
}
TestShape.ts
/// <reference path="IShape.ts" />
/// <reference path="Circle.ts" />
/// <reference path="Triangle.ts" />
function drawAllShapes(shape:Drawing.IShape){
shape.draw();
}
drawAllShapes(new Drawing.Circle())
drawAllShapes(new Drawing.Triangle())
编译 tsc --out app.js TestShape.ts
嵌套命名空间:成员的访问使用点号.来实现
模块
IShape.ts
export interface IShape {
draw();
}
Circle.ts
import shape = require("./IShape");
export class Circle implements shape.IShape {
public draw() {
console.log("Circle is drawn")
}
}
Triangle.ts
import shape = require("./IShape");
export class Triangle implements shape.IShape {
public draw() {
console.log("Triangle is drawn")
}
}
TestShape.ts
import shape = require("./IShape");
import circle = require("./Circle");
import triangle = require("./Triangle");
function drawAllShapes(shapeToDraw:shape.IShape){
shapeToDraw.draw();
}
drawAllShapes(new circle.Circle())
drawAllShapes(new triangle.Triangle())
tsc --module amd TestShape.ts
tsc --module commonjs TestShape.ts
声明文件
使用第三方库
jQuery: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/jquery/index.d.ts
CalcThirdPartyJsLib.js
var Cyan;
(function(Cyan) {
var Calc = (function () {
function Calc() {
}
})
Calc.prototype.doSum = function (limit) {
var sum = 0;
for (var i = 0; i <= limit; i++) {
sum = sum + i;
}
return sum;
}
Cyan.Calc = Calc;
return Calc;
})(Cyan || (Cyan = {}));
var test = new Cyan.Calc();
Calc.d.ts
declare module Cyan {
export class Calc {
doSum(limit:number) : number;
}
}
CalcTest.ts
/// <reference path = "Calc.d.ts" />
var obj = new Cyan.Calc();
console.log(obj.doSum(100));
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>index</title>
<script src = "CalcThirdPartyJsLib.js"></script>
<script src = "CalcTest.js"></script>
</head>
<body>
<h1>声明文件测试</h1>
<p>测试一下。</p>
</body>
</html>
最后
以上就是稳重金鱼为你收集整理的TypeScript基础的全部内容,希望文章能够帮你解决TypeScript基础所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复