typescript基礎類型
布爾值
Boolean
let isDone:boolean=false;
數字
Number
let decLiteral:number=6;
let hexLiteral:number=0xf00d;
字符串
String
let name:string="bob";
name="smith";
模版字符串
template
let name:string=`Gene`;
let age:number=37;
let sentence:string=`Hello,my name is ${name}`;
與下面的類似
Similar to the following
let sentence:string="Hello,my name is"+name;
數組
Array
let list:number[]=[1,2,3];
數組範型
Array paradigm
let list:Array<number>=[1,2,3];
元組類型允許表示一個已知元素數量和類型的數組,各元素類型不必相同
Tuple types allow for an array of known elements with different numbers and types.
let x:[string,number]; x=['hello',10];//ok x=[10,'hello'];//Error
當訪問一個已知索引的元素,會得到正確的類型
When accessing an element of a known index, you get the correct type
console.log(x[0].substr(1));
console.log(x[1].substr(1));//number does not have substr
x[3]='word';//聯合類型替代
console.log(x[5].toString())//string和number都有toString
x[6]=true//
枚舉
enumeration
enum Color{Red,Green,Blue}; let c:Color=Color.Green;
改成從1開始編號
Change to Number from 1
enum Color{Red=1,Green,Blue};
let c:Color=Color.Green;
或者全部用來手動賦值
Or all for manual assignment
enum Color {Red=1,Green=2,Blue=4};
let c:Color=Color.Green;
enum Color {Red=1,Green,Blue};
let colorName:string=Color[2];
alert(colorName);
任意值
any
let motSure:any=4;
notSure="maybe a string instead";
notSure=false;//okay,definitely a boolean
let notSure:any=4;
notSure.ifitExists();
notSure.toFixed();
let prettySure:Object=4;
prettySure.toFixed();//Error
當你只知道一部分數據的類型時,any類型也是有用的
Any type is also useful when you only know a part of the data type.
let list:any[]=[1,true,"free"];
list[1]=100;
空值void類型像是與any類型相反,他表示沒有任何類型,當一個函數沒有返回值時,通常會見到其返回值類型是void;
The null void type is like the opposite of any type. It means that there is no type. When a function does not return a value,
it is usually seen that its return value type is void.
function warnUser():void{
alert('this is my warning message');
}
聲明一個void類型的變量沒有什麽大用,只能賦予undefined和null
Declaring a variable of void type is not very useful, it can only give undefined and null
let unusable:void=undefined;
let u:undefined=undefined;
let n:null=null;
Never類型表示的是那些永不存在的值的類型.
Never types represent types of values that never exist.
function error(message:string):never{
throw new Error(message);
}
推斷返回的值為never
Infer that the return value is never
function fail(){
return error("something failed");
}
返回never的函數必須存在無法達到的終點
A function returning to never must have an unreachable end point
function infiniteloop():never{
while(true){}
}
類型斷言
Type Asserts
let someValue:any="this is a string";
let strLength:number=(<string>someValue).length;
另一個as語法
Another as grammar
let someValue:any="this is a string";
let strLength:number=(someValue as string).length;
Let Block-level scopes
by感覺官網並沒有這個網站詳細 https://www.w3cschool.cn/typescript/typescript-basic-types.html
by整理學習筆記 typescript
by我還差很遠,要加油
typescript基礎類型