TypeScript入門這篇不夠H浮!忿峻!

一薄啥、安裝

全局安裝typescript(默認(rèn)你已經(jīng)安裝了node)

<pre class="hljs nginx" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 0.75em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">npm install -g typescript
復(fù)制代碼</pre>

安裝完了以后,就可以使用 typescript 進(jìn)行開發(fā)了

<pre class="prettyprint hljs javascript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">// demo.ts
function demo01() {
let test: string = 'a test typescript';
console.log(test)
}
demo01()
復(fù)制代碼</pre>

typescript結(jié)尾的.ts文件是不能直接運(yùn)行的逛尚,需要編譯為.js結(jié)尾的文件才能運(yùn)行

編譯方式:

<pre class="prettyprint hljs vim" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">// 先編譯為js文件

// 編譯
tsc demo.ts
// 執(zhí)行
node demo.js

// 使用ts-node插件的方式直接執(zhí)行.ts文件
npm install -g ts-node
ts-node demo.ts // 直接運(yùn)行ts文件
復(fù)制代碼</pre>

二垄惧、靜態(tài)類型

<pre class="hljs typescript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 0.75em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">// demo2.ts
const count : number = 1;
復(fù)制代碼</pre>

這里定義了 count 變量,這里的 : number 就是定義了一個(gè)靜態(tài)類型绰寞。

注意:warning::靜態(tài)變量的類型不可以改變到逊,但是值是可以改變的。

自定義靜態(tài)類型

<pre class="prettyprint hljs typescript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">...
interface Demo {
name: string;
age: number;
}

let demo : Demo = {
name: '23',
age: 23
}
console.log(demo);...
復(fù)制代碼</pre>

三滤钱、數(shù)據(jù)類型

基礎(chǔ)數(shù)據(jù)類型: number 觉壶、 stringboolean 件缸、 null 铜靶、 undefinedsymbol

對(duì)象類型:對(duì)象他炊、數(shù)組争剿、類已艰、函數(shù)

Number

TypeScript 里的所有數(shù)字都是浮點(diǎn)數(shù)。 這些浮點(diǎn)數(shù)的類型是 number 蚕苇。 除了支持十進(jìn)制和十六進(jìn)制字面量旗芬,TypeScript 還支持 ECMAScript 2015 中引入的二進(jìn)制和八進(jìn)制字面量。

<pre class="prettyprint hljs typescript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">let num : number = 11111;
let hexLiteral: number = 0xf00d;
let binaryLiteral: number = 0b1010;
let octalLiteral: number = 0o744;
復(fù)制代碼</pre>

String

<pre class="prettyprint hljs verilog" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">let str : string = '這是string基礎(chǔ)靜態(tài)類型';
let str1 : string = "這是基礎(chǔ)數(shù)據(jù)類型";
復(fù)制代碼</pre>

Boolean

<pre class="hljs rust" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 0.75em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">let bool : boolean = true;
復(fù)制代碼</pre>

Null

<pre class="hljs fsharp" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 0.75em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">let nul : null = null;
復(fù)制代碼</pre>

Undefined

<pre class="hljs javascript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 0.75em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">let unde : undefined = undefined;
復(fù)制代碼</pre>

Symbol

<pre class="prettyprint hljs javascript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">let sym : symbol = Symbol('foo');
let sym1 : symbol = Symbol(123);
復(fù)制代碼</pre>

對(duì)象

<pre class="prettyprint hljs yaml" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">let obj : {
user: string,
age: number,
sex: boolean
} = {
user: 'xiaoming',
age: 26,
sex: true
}
console.log(obj) // { user: 'xiaoming', age: 26, sex: true }
復(fù)制代碼</pre>

數(shù)組

TypeScript像JavaScript一樣可以操作數(shù)組元素捆蜀。 有兩種方式可以定義數(shù)組疮丛。 第一種,可以在元素類型后面接上 [] 辆它,表示由此類型元素組成的一個(gè)數(shù)組

<pre class="prettyprint hljs typescript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">// 直接[]方式
let arr : Object[] = [null, undefined, 0, '123', true];
let arr1 : String[] = ['null', 'undefined', '0', '123', "true"];
console.log(arr) // [ null, undefined, 0, '123', true ]
console.log(arr1) // [ 'null', 'undefined', '0', '123', 'true' ]

// 數(shù)組范型誊薄, Array<元素類型>

const arr3: Array<string> = ['str', 'strr', 'strrr'];
復(fù)制代碼</pre>

函數(shù)

<pre class="prettyprint hljs javascript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">let func : () => string = () => '小明' // es6箭頭函數(shù)
console.log(func) // [Function: func]
復(fù)制代碼</pre>

<pre class="prettyprint hljs javascript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">class Person {}

let per : Person = new Date(); // new Date() 也是可以,并沒有報(bào)錯(cuò)
const per1 : Person = new Person();
console.log(per) // 2020-09-16T11:23:19.698Z
console.log(per1) // Person {}
復(fù)制代碼</pre>

enum枚舉

<pre class="prettyprint hljs typescript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">// dmeo.ts
enum Color {Red, Green, Blue}
let c: Color = Color.Green
let r: Color = Color.Red
let b: Color = Color.Blue

// demo.js
var Color;
(function (Color) {
Color[Color["Red"] = 0] = "Red";
Color[Color["Green"] = 1] = "Green";
Color[Color["Blue"] = 2] = "Blue";
})(Color || (Color = {}));
var c = Color.Green;
var r = Color.Red;
var b = Color.Blue;
console.log(c, b, r);

console.log(Color) // { '0': 'Red', '1': 'Green', '2': 'Blue', Red: 0, Green: 1, Blue: 2 }
console.log(c, b, r) // 1 2 0 r是0锰茉,是因?yàn)槟J(rèn)是從0開始

// key呢蔫、value簡(jiǎn)直是你中有我,我中有你飒筑,這就是枚舉
//-----------------------------------------------
// 修改起始順序
enum Colors {Pink = 1, Yellow, Purple}
let p: Colors = Colors.Pink
let y: Colors = Colors.Yellow
let p1: Colors = Colors.Purple
console.log(p,y,p1) // 1 2 3
console.log(Colors)
/{
'1': 'Pink',
'2': 'Yellow',
'3': 'Purple',
Pink: 1,
Yellow: 2,
Purple: 3
}
/

// 對(duì)應(yīng)的js
var Colors;
(function (Colors) {
Colors[Colors["Pink"] = 1] = "Pink";
Colors[Colors["Yellow"] = 2] = "Yellow";
Colors[Colors["Purple"] = 3] = "Purple";
})(Colors || (Colors = {}));
var p = Colors.Pink;
var y = Colors.Yellow;
var p1 = Colors.Purple;
console.log(p, y, p1); // 1 2 3
console.log(Colors);

//-----------------------------------------------

// 修改沒個(gè)值
enum Job {Fe = 12, Php = 1, Java = 4}
let f: Job = Job.Fe;
let p3: Job = Job.Php;
let j: Job = Job.Java;
let fe: string = Job[12];
let php: string = Job[1];
let java: string = Job[4];

console.log(f,p3,j,fe,php,java) // 12 1 4 Fe Php Java
console.log(Job) // { '1': 'Php', '4': 'Java', '12': 'Fe', Fe: 12, Php: 1, Java: 4 }
/*

*/

// 對(duì)應(yīng)的js
var Job;
(function (Job) {
Job[Job["Fe"] = 12] = "Fe";
Job[Job["Php"] = 1] = "Php";
Job[Job["Java"] = 4] = "Java";
})(Job || (Job = {}));
var f = Job.Fe;
var p3 = Job.Php;
var j = Job.Java;
var fe = Job[12];
var php = Job[1];
var java = Job[4];
console.log(f, p3, j, fe, php, java); // 12 1 4 Fe Php Java
復(fù)制代碼</pre>

以上就是枚舉的舉例片吊,同理,我是不是可以理解下面對(duì)于js來(lái)說(shuō)就是枚舉 ??

<pre class="hljs less" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 0.75em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">{
4: 'java',
34: 'php',
2: 'js'
}
復(fù)制代碼</pre>

Any

有時(shí)候协屡,我們會(huì)想要為那些在編程階段還不清楚類型的變量指定一個(gè)類型俏脊。 這些值可能來(lái)自于動(dòng)態(tài)的內(nèi)容,比如來(lái)自用戶輸入或第三方代碼庫(kù)肤晓。 這種情況下爷贫,我們不希望類型檢查器對(duì)這些值進(jìn)行檢查而是直接讓它們通過(guò)編譯階段的檢查。 那么我們可以使用 any 類型來(lái)標(biāo)記這些變量

<pre class="prettyprint hljs typescript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false; // okay, definitely a boolean

// 下面是官網(wǎng)的例子补憾,但是報(bào)錯(cuò)(這就很迷茫了:joy:)
let notSure: any = 4;
notSure.ifItExists(); // okay, ifItExists might exist at runtime
notSure.toFixed();

let prettySure: Object = 4;
prettySure.toFixed(); // Error: Property 'toFixed' doesn't exist on type 'Object'.

// 當(dāng)你只知道一部分?jǐn)?shù)據(jù)的類型時(shí)漫萄,any類型也是有用的。 比如盈匾,你有一個(gè)數(shù)組腾务,它包含了不同的類型的數(shù)據(jù)
let list: any[] = [1, true, "free"];
list[1] = 100;
復(fù)制代碼</pre>

image

Nerver

never 類型表示的是那些永不存在的值的類型。 例如削饵, never 類型是那些總是會(huì)拋出異逞沂荩或根本就不會(huì)有返回值的函數(shù)表達(dá)式或箭頭函數(shù)表達(dá)式的返回值類型; 變量也可能是 never 類型葵孤,當(dāng)它們被永不為真的類型保護(hù)所約束時(shí)担钮。

never 類型是任何類型的子類型,也可以賦值給任何類型尤仍;然而箫津,

沒有

類型是 never 的子類型或可以賦值給 never 類型(除了 never 本身之外)。 即使 any 也不可以賦值給 never

下面是一些返回 never 類型的函數(shù):

<pre class="prettyprint hljs javascript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">// 返回never的函數(shù)必須存在無(wú)法達(dá)到的終點(diǎn)
function error(message: string): never {
throw new Error(message);
}

// 推斷的返回值類型為never
function fail() {
return error("Something failed");
}

// 返回never的函數(shù)必須存在無(wú)法達(dá)到的終點(diǎn)
function infiniteLoop(): never {
while (true) {
}
}
復(fù)制代碼</pre>

Object

object 表示非原始類型苏遥,也就是除 number 饼拍, stringboolean 田炭, symbol 师抄, nullundefined 之外的類型。

使用 object 類型教硫,就可以更好的表示像 Object.create 這樣的API叨吮。例如:

<pre class="prettyprint hljs sql" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">declare function create(o: object | null): void;

create({ prop: 0 }); // OK
create(null); // OK

create(42); // Error
create("string"); // Error
create(false); // Error
create(undefined); // Error
復(fù)制代碼</pre>

類型斷言

<pre class="prettyprint hljs typescript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">// 第一種尖括號(hào)的方式
let someValue: any = "this is a string";

let strLength: number = (<string>someValue).length;

// 第二種as方式
let someValue: any = "this is a string";

let strLength: number = (someValue as string).length;
復(fù)制代碼</pre>

注意:warning:: 當(dāng)你在TypeScript里使用JSX時(shí),只有 as 語(yǔ)法斷言是被允許的

四瞬矩、類型注釋和類型推斷

類型注釋

這種就是 類型注釋

<pre class="hljs swift" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 0.75em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">let count : number = 23;
復(fù)制代碼</pre>

類型推斷

不寫數(shù)據(jù)需要的類型茶鉴,但是系統(tǒng)字段推斷為 number 類型,這就是 類型推斷 景用。在這里涵叮,沒寫類型注釋街氢,但是ts依然識(shí)別出count1是 number 類型哨啃,就好比反推,這種情況叫做類型推斷怎静。

<pre class="hljs xquery" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 0.75em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">let count1 = 24;
復(fù)制代碼</pre>

寫不寫類型注釋媚污,根據(jù)業(yè)務(wù)自身去確定舀瓢,比如計(jì)算2個(gè)數(shù)的和,如果不寫注釋傳入字符串的話就是拼接了杠步,所以要靈活根據(jù)業(yè)務(wù)自身去確定寫不寫類型注釋氢伟。

<pre class="prettyprint hljs typescript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">// 這里是計(jì)算功能,是需要寫的幽歼,否則就是字符串的拼接功能了。
function sumTwo(one : number, two : number) {
return one + two;
}
console.log(sumTwo(2,3)); // 5
// console.log(sumTwo('2','3')); // 報(bào)錯(cuò)
復(fù)制代碼</pre>

五谬盐、函數(shù)參數(shù)和返回類型定義

參數(shù)

基礎(chǔ)數(shù)據(jù)類型

<pre class="prettyprint hljs javascript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">// 2個(gè)簡(jiǎn)單的例子甸私,其他的類似

function echo(str : string) {
console.log(str)
}
function echo1(bool : boolean) {
console.log('打印的值是:' + (bool ? '真' : '假的'));
}
echo('he is a huamen'); // he is a huamen
echo1(true); // 打印的值是:真
echo1(false); // 打印的值是:假的
復(fù)制代碼</pre>

對(duì)象類型

<pre class="prettyprint hljs javascript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">// 參數(shù)是數(shù)組
function echo2(str3 : Object []) {
console.log(str3)
}

// 參數(shù)是對(duì)象
function echo3({one, two} : {one: string, two: string}) {
console.log(one + two)
}

// 參數(shù)是函數(shù)
function echo4(str : () => "33") {
str()
}

// 參數(shù)是類
function echo5(time : Date) {
console.log(time.getTime())
}

echo2([null, undefined, 0, true]); // [ null, undefined, 0, true ]
echo3({one: '3', two: '55'}); // 355
echo4(function () {
return '33';
}); // undefined
echo5(new Date()); // 1600256196949
復(fù)制代碼</pre>

返回值

無(wú)返回值

函數(shù)無(wú)返回值,給函數(shù)增加類型注釋 void 即可

<pre class="prettyprint hljs livescript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">function echo6() : void {
console.log('這個(gè)函數(shù)是沒返回值')

// return 3333; // 直接報(bào)錯(cuò)Type 'number' is not assignable to type 'void'.
}
echo6();
復(fù)制代碼</pre>

基礎(chǔ)基礎(chǔ)數(shù)據(jù)類型

<pre class="prettyprint hljs javascript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">function echo7(num : number) : boolean {
return num > 0;
}

console.log(echo7(9)); // true
console.log(echo7(-23)); // false
復(fù)制代碼</pre>

對(duì)象類型

<pre class="prettyprint hljs lua" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">// 下面是返回個(gè)string類型的數(shù)組,其他的類似
function echo8() : string[] {
return ['1', '2', 'str', 'num'];
}
console.log(echo8()) // [ '1', '2', 'str', 'num' ]
復(fù)制代碼</pre>

六飞傀、數(shù)組類型

簡(jiǎn)單類型

<pre class="prettyprint hljs lua" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">let arr : string[] = ['1','3', 'erder', 'sfesrfre'];
console.log(arr) // [ '1', '3', 'erder', 'sfesrfre' ]
復(fù)制代碼</pre>

一般api返回的都是數(shù)組或者對(duì)象皇型,因此如何定義對(duì)象類型是個(gè)重點(diǎn)!T曳场弃鸦!

<pre class="prettyprint hljs groovy" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">// 如下看起來(lái)可以解決, 但是不夠通用幢痘,再來(lái)一個(gè)同樣的數(shù)組唬格,那定義的類型就要在寫一遍,由此ts為我們準(zhǔn)備一個(gè)概念:類型別名(定義的時(shí)候要以type關(guān)鍵字開始)!
// 這里的類型:類型別名购岗、接口汰聋、類都是可以解決的!
let arr1 : {user: string, age: number}[] = [
{user: 'x', age: 23},
{user: 'y', age: 24},
];

console.log(arr1) // [ { user: 'x', age: 23 }, { user: 'y', age: 24 } ]
復(fù)制代碼</pre>

數(shù)組包含多種類型

<pre class="prettyprint hljs typescript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">const xiaojiejie1 : (string | number)[] = ['dajiao',28, 'teacher'] // 不是元組喊积,不能定位到每個(gè)元素的類型烹困,調(diào)換順序不會(huì)報(bào)錯(cuò)。
復(fù)制代碼</pre>

類型別名

以關(guān)鍵字 type 開始

<pre class="prettyprint hljs groovy" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">// 類型別名
type male = {
name: string,
age: number
}

// 接口
interface female {
user: String;
age: Number;
}

// 類
class Demo {
name: string
age: number
};

let arr2 : male[] = [
{name: 'aaa', sex: true},
{name: 'bbb', sex: true},
{name: 'ccc', sex: !!'true'}
]
console.log(arr2)

let arr3 : female[] = [
{user: 'abbb', age: 23},
{user: 'accc', age: 24},
{user: 'addd', age: 26}
]
console.log(arr3)

let arr4 : Demo[] = [
{name: 'xiaoming', age: 23},
{name: 'xiaoshi', age: 23},
{name: 'xiaohong', age: 23},
{name: 'xiaoguang', age: 23}
]
console.log(arr4)
復(fù)制代碼</pre>

七乾吻、元組

<pre class="prettyprint hljs typescript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">const xiaojiejie : [string,string ,number] = ['dajiao','teacher',28]
// 這就是一個(gè)元組髓梅,定義了每個(gè)字段的類型,如果順序變化了绎签,就會(huì)報(bào)錯(cuò)女淑。
// 這是一個(gè)多維數(shù)組的元組
const xiao3 : [string, string, number][] = [
['x', 'te', 3],
['x', 'te', 3],
['x', 'te', 3],
['x', 'te', 3],
]
console.log(xiao3) //
復(fù)制代碼</pre>

八、interface接口

定義

<pre class="prettyprint hljs groovy" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">// 定義一個(gè)函數(shù)
const findXiao = (name: string, age: number, must: number) => {
age < 24 && must > 90 && console.log('錄取')
age > 24 && must < 90 && console.log('淘汰')
}
const xiao = {name: '老謝', age: 21, must: 99}
const xiao1 = {name: '老謝', age: 89, must: 09}
findXiao('辣蟹', 21, 99) // 錄取
復(fù)制代碼</pre>

同樣的問(wèn)題辜御,每次都寫的話鸭你,人要累死了:cry:

<pre class="prettyprint hljs typescript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">// 提取為interface
interface Gril {
name: string;
age: number;
must: number;
}

const xiao = {name: '老謝', age: 21, must: 99}
const xiao1 = {name: '老謝', age: 89, must: 09}

const findXiao1 = (gril : Gril) => {
gril.age < 30 && gril.must > 90 && console.log("預(yù)錄取")
gril.age > 30 && gril.must < 90 && console.log("預(yù)不錄取")
}
findXiao1(xiao) // 預(yù)錄取
findXiao1(xiao1) // 預(yù)不錄取
復(fù)制代碼</pre>

interface和類型別名區(qū)別

類型別名是可以直接給類型,比如: type Gril = string;

interface 必須是對(duì)象

接口非必選值定義

<pre class="prettyprint hljs typescript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">interface Gril1 {
name: string;
age: number;
must: number;
leg ?: string; // 接口非必選值定義
}

const findXiao2 = (gril : Gril1) => {
gril.age < 30 && gril.must > 90 && console.log("預(yù)錄取")
gril.age > 30 && gril.must < 90 && console.log("預(yù)不錄取")
gril.leg && console.log('我看到你的大長(zhǎng)腿了')
}

const xiao2 = {name: '老謝', age: 89, must: 09, leg: "haha"}
findXiao2(xiao2)
// 預(yù)不錄取
//我看到你的大長(zhǎng)腿了
復(fù)制代碼</pre>

接口增加任意參數(shù)和方法

<pre class="prettyprint hljs typescript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">interface Gril2 {
name: string;
age: number;
must: number;
leg ?: string; // 接口非必選值定義
[propname:string] : any; // 允許加入任意值擒权,不像上面的那么嚴(yán)格
say(): string; // 增加了一個(gè)say方法袱巨,返回值是string類型
}
復(fù)制代碼</pre>

類繼承接口(implements)

<pre class="prettyprint hljs dart" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">class Xiao3 implements Gril2 {
name = 'zhy'
age = 23
must = 99
say() {
return this.name
}
}
console.log(new Xiao3()) // Xiao3 { name: 'zhy', age: 23, must: 99 }
復(fù)制代碼</pre>

接口繼承接口(extends)

<pre class="hljs dart" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 0.75em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">interface Xiao4 extends Gril2{

}
復(fù)制代碼</pre>

九、類

定義

<pre class="prettyprint hljs javascript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">class Lady {
content = 'say hi'
say() {
return this.content
}
}

const xiaohong = new Lady();
console.log(xiaohong.say()) // say hi
復(fù)制代碼</pre>

繼承和方法重寫

super 關(guān)鍵字支持使用父類的方法碳抄,但是不能使用屬性

<pre class="prettyprint hljs scala" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">class Zhang extends Lady {
say() {
return '這里是Zhang的重寫';
}

walk() {
console.log('1111111111super', super.say()) // 方法是可以的
// console.log('1111111111super', super.content) // 報(bào)錯(cuò)愉老,屬性不行
return '邊走鞭炮';
}
}

const xiaozhang = new Zhang();
console.log(xiaozhang.content) // say hi
console.log(xiaozhang.say()) // 這里是Zhang的重寫
console.log(xiaozhang.walk()) // 1111111111super say hi
復(fù)制代碼</pre>

super使用父類的方法

訪問(wèn)限制符public,protected,private

public : 類的內(nèi)部和外部都可以訪問(wèn)

protected :類的內(nèi)部和子類可以訪問(wèn)

private : 只能在自己本類內(nèi)部訪問(wèn)

<pre class="prettyprint hljs scala" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">class Person {
public name : string
public say() {
return this.name
}
}
const zhy = new Person();
zhy.name = 'haiyang';
console.log(zhy.say()) // haiyang

class Person1 {
protected name : string = 'yangyang'
public say() {
return this.name
}
}
const zhy1 = new Person1();
// zhy1.name = 'haiyang'; // 報(bào)錯(cuò),Property 'name' is protected and only accessible within class 'Person1' and its subclasses.
console.log(zhy1.say()) // yangyang

class Person2 extends Person1 {
public walk() {
return this.name
}
}
const zhy2 = new Person2()
console.log(zhy2.walk()) // yangyang

class Person3 {
private name : string = 'haihai'
public say() {
return this.name
}
}
const zhy3 = new Person3();
// zhy3.name = 'haiyang'; // 報(bào)錯(cuò)剖效,Property 'name' is private and only accessible within class 'Person3
console.log(zhy3.say()) // haihai

class Person4 extends Person3{
walk() {
// return this.name //報(bào)錯(cuò)嫉入, 09_calss.ts:78:17 - error TS2341: Property 'name' is private and only accessible within class 'Person3'.
}
}
const zhy4 = new Person4()
console.log(zhy4.walk()) // undefined
復(fù)制代碼</pre>

構(gòu)造函數(shù)

<pre class="prettyprint hljs scala" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">class Now{

}

class Chl extends Now {
constructor() {
super() // 報(bào)錯(cuò)才補(bǔ)的
//因?yàn)闆]寫super(),所以報(bào)錯(cuò)了, Constructors for derived classes must contain a 'super' call.
console.log(1111)
}
}
const c = new Chl();
復(fù)制代碼</pre>

getter,setter,static用法

  1. getter 璧尸、 setter 都是屬性咒林,只是形式函數(shù)

2. 屬性的名字可以是隨意的,你自己知道對(duì)應(yīng)的意思就好

<pre class="prettyprint hljs typescript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">class Xie {
constructor(private num_age : number) {

}

// 屬性的名字是隨意的爷光,此時(shí)看著是方法垫竞,但對(duì)于類來(lái)說(shuō)只是一個(gè)屬性
set name(age : number) {
this.num_age = age
}

get age() {
return this.num_age
}
}

const xiaoxie = new Xie(32)
console.log(xiaoxie.age) //32 注意是屬性!V颉欢瞪!
xiaoxie.name = 4444 // 注意是屬性!P炻恪遣鼓!
console.log(xiaoxie.age) // 4444 上面改變了年齡

/*
1. 靜態(tài)屬性和方法只是不應(yīng)實(shí)例化類,而類可以直接調(diào)用
*/

class StaticClass {
name = 'zhy'
static age = 23
say() {
console.log('我不是static的方法')
}
static walk() {
console.log('我是static重贺,并且可以在外部使用的方法')
}
}
console.log(StaticClass.name) // StaticClass 這個(gè)應(yīng)是固有的屬性骑祟,獲取方法名字
console.log(StaticClass.age) // 23
// console.log(StaticClass.say()) // 不可以訪問(wèn)回懦,會(huì)報(bào)錯(cuò)
console.log(StaticClass.walk()) // 我是static,并且可以在外部使用的方法
復(fù)制代碼</pre>

只讀屬性和抽象類

只讀屬性

關(guān)鍵字readonly

<pre class="prettyprint hljs typescript" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">class Person10 {
public readonly _name :string;
constructor(name:string) {
this._name = name;
}
}

const person10 = new Person10('demo')
// person10._name= '謝廣坤' // 報(bào)錯(cuò)曾我,Cannot assign to '_name' because it is a read-only property.
console.log(person10._name) // demo
復(fù)制代碼</pre>

抽象類

1. 關(guān)鍵字abstract定義類

2. 抽象方法不能有方法體

3. 子類必須實(shí)現(xiàn)抽象方法

4. 抽象類里面可以有其他正常類的屬性和方法(根據(jù)php推出)

<pre class="prettyprint hljs scala" style="padding: 0.5em; font-family: Menlo, Monaco, Consolas, "Courier New", monospace; color: rgb(68, 68, 68); border-radius: 4px; display: block; margin: 0px 0px 1.5em; font-size: 14px; line-height: 1.5em; word-break: break-all; overflow-wrap: break-word; white-space: pre; background-color: rgb(246, 246, 246); border: none; overflow-x: auto;">abstract class Girl{
abstract skill() //因?yàn)闆]有具體的方法粉怕,所以我們這里不寫括號(hào)

}
class Waiter extends Girl{
skill(){
console.log('大爺,請(qǐng)喝水抒巢!')
}
}

class BaseTeacher extends Girl{
skill(){
console.log('大爺贫贝,來(lái)個(gè)泰式按摩吧!')
}
}

class seniorTeacher extends Girl{
skill(){
console.log('大爺蛉谜,來(lái)個(gè)SPA全身按摩吧稚晚!')
}
}

abstract class Girl{
name = 'zhy'
say() {
return 333;
}
abstract skill() //因?yàn)闆]有具體的方法,所以我們這里不寫括號(hào)

}
復(fù)制代碼</pre>

image
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末型诚,一起剝皮案震驚了整個(gè)濱河市客燕,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌狰贯,老刑警劉巖也搓,帶你破解...
    沈念sama閱讀 221,695評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異涵紊,居然都是意外死亡傍妒,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,569評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門摸柄,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)颤练,“玉大人,你說(shuō)我怎么就攤上這事驱负∴戮粒” “怎么了?”我有些...
    開封第一講書人閱讀 168,130評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵跃脊,是天一觀的道長(zhǎng)宇挫。 經(jīng)常有香客問(wèn)我,道長(zhǎng)匾乓,這世上最難降的妖魔是什么捞稿? 我笑而不...
    開封第一講書人閱讀 59,648評(píng)論 1 297
  • 正文 為了忘掉前任,我火速辦了婚禮拼缝,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘彰亥。我一直安慰自己咧七,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,655評(píng)論 6 397
  • 文/花漫 我一把揭開白布任斋。 她就那樣靜靜地躺著继阻,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上瘟檩,一...
    開封第一講書人閱讀 52,268評(píng)論 1 309
  • 那天抹缕,我揣著相機(jī)與錄音,去河邊找鬼墨辛。 笑死卓研,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的睹簇。 我是一名探鬼主播奏赘,決...
    沈念sama閱讀 40,835評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼太惠!你這毒婦竟也來(lái)了磨淌?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,740評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤凿渊,失蹤者是張志新(化名)和其女友劉穎梁只,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體埃脏,經(jīng)...
    沈念sama閱讀 46,286評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡搪锣,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,375評(píng)論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了剂癌。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片淤翔。...
    茶點(diǎn)故事閱讀 40,505評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖佩谷,靈堂內(nèi)的尸體忽然破棺而出旁壮,到底是詐尸還是另有隱情,我是刑警寧澤谐檀,帶...
    沈念sama閱讀 36,185評(píng)論 5 350
  • 正文 年R本政府宣布抡谐,位于F島的核電站,受9級(jí)特大地震影響桐猬,放射性物質(zhì)發(fā)生泄漏麦撵。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,873評(píng)論 3 333
  • 文/蒙蒙 一溃肪、第九天 我趴在偏房一處隱蔽的房頂上張望免胃。 院中可真熱鬧,春花似錦惫撰、人聲如沸羔沙。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,357評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)扼雏。三九已至坚嗜,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間诗充,已是汗流浹背苍蔬。 一陣腳步聲響...
    開封第一講書人閱讀 33,466評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留蝴蜓,地道東北人碟绑。 一個(gè)月前我還...
    沈念sama閱讀 48,921評(píng)論 3 376
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像励翼,于是被迫代替她去往敵國(guó)和親蜈敢。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,515評(píng)論 2 359