使用 TypeScript 写 React 1/30 之认识 TypeScript!!!

介绍TypeScript

就我所了解的TypeScript,它有点像是强化版本的JavaScript,例如说:你在JavaScript中写一个Function,你带入的参数在你的假想中它的型别为数字,但是当你带入的资料为文字的时候,它不会显示你因为型别错误而导致你的Function错误的,然后你就要找哪里有错误就话多话一阵子的时间,好比说:

    const add = (a, b) => a + b;    你预期中的呈现方式:    add(2, 3); return 5    但是当资料为文字的时候,    add('I', 'am'); return 'Iam'    还是可以动!!这就是JavaSript强大的地方~~(误)~~

但是当使用TypeScript的时候就不会有这种问题发生,例如:

    const add = (a: number, b: number) => a + b ;    add('Y', 'ou'); 显示a ,b type not number    当你带入的值不是number的时候它会跑出提醒你的参数不为number;

这样很明显就知道是型别的问题,而不用再去找问题点在哪,当然这只是TypeScript强大的地方之一!由于小弟最近在忙着赶专案,今天就来简易介绍TypeScript有哪些Type,求各位大大鞭小力一点,有甚么错误的立方再麻烦提点一下!!


TypeScript 的型别

Boolean

true/false, 我相信这大家很常见!!

let open: boolean = true;

Number

Number有判别不只是数字,它包括:( hexadecimal/ decimal literals/ binary/ octal literals ...etc,我现在才知道原来不只有识别数字原来有来其它的!!

let decimal: number = 5; // decimal literalslet hex: number = 0xf00d; // hexadecimallet binary: number = 0b1010; // binarylet octal: number = 0o744;  // octal literalslet big: bigint = 100n; //Bibint 有点像是大数字之类的意思

String

这个易懂--文字!!

cont lange: string = "English" cont other: string = `I am ${name}`const otherTwo: string = "I am" + "Jay"

Array

它的组合很多,有文字阵列,数字...etc

1. let numberArray: number[] = [1, 2, 3];2. let numerArrayTwo: Array<number> = [4, 5, 6];

Tuple

它像是Array的大杂烩,假如你的Array中有包含string跟number...等等

let mixArray: [x: number, y: string] = [123, "number"];mixArray = ["string", 123]; //这样是不行的要跟上面的位置一模一样!!不然会跳错误mixArray.[2] = 1;//这样也是不行得因为你设定的长度只有2,不能大于你预设的长度

Enum

尚未完全理解!!待补充!!
Loading ...

Unknow

当你的变数不知道回传是甚么type的时候可以使用它,但是它不为任何型别。

let a: unknow = 4;a = true;a = "country";a = 10;const numberA: number = a; //它跳错误 a type not number

Any

any像是甚么都可以,但是还是少用any不然这样使用TypeScript很没效果

let anyType: any = 'a';anyType = 5;

Void

function no return value or value === null | undefined!

const add = ():void => console.log("123");let value:void = undefined;vlaue = null;

Null and Undefined

Null 跟 undefined 有自己的型别不过跟void很像!!不过这很少单独使用,比较常跟其它混合使用

let a : string | null = "a";

Never

有点像是没有停止的function或者是当function还会传至下一个funciton 或者动作时候可以使用

const error = (message: string): never => { throw new Error(message)};const neverStop = (): never => { while(true){...} };

Object

这看程式比较好懂,就我理解就是object

const create = (obj: object | null):void;create({a: 0}); //OK!!create(1); // not ok

以上就是基本的TypeScript的型别!!有任何错误可以多多提醒我一下感恩!!

引用(https://www.typescriptlang.org/docs/handbook/basic-types.html)


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章