String string 区别
const msg: string = 'hello';
const message: String = 'hello';
export {};
这边冒号后面的类型是区分开来的
strinig: 代表 ts 中的字符串类型
String: 代表 js 中字符串包装类的类型
let foo = 'cqc';
foo = 123456;
数据类型 ( js 中存在的 )
默认情况下如果可以推导出(infer)标识符的类型时候 一般不手动加类型
数值 number
let num1: number = 213;
let num2: number = 0b111;
let num3: number = 0o456;
let num4: number = 0x9ac;
布尔 boolean
let flag1 = 2 > 3;
let flag2 = false;
字符 string
数组 Array
const arr1: Array<string> = ['cqc'];
const arr2: string[] = ['cqc'];
对象 object
const info1 = {
name: 'cqc',
age: 24,
const info2: object = {
name: 'cqc',
空值 null
const nl: null = null;
未定义 undefined
const und: undefined = undefined;
唯一 symbol
数据类型 ( ts 中独有的 )
当进行一些类型断言的时候 as any 否则报错
在不想给某些 js 添加具体数据类型时候 any-script?
const arr: any[] = [];
unknown
类似 any 类型, 用于不确定类型
在不能推导出来的时候使用 (可能是类型 a 可能是类型 b)
unknown、any 区别
unknown 类型的数据只能赋值给 unknown 类型 或者 any 类型, 但是 any 类型可以赋值任意类型
let unknown1: unknown;
let any1: any;
const str1: string = any1;
const str2: string = unknown1;
const foo = function (str: string): void {
return null || undefined;
never
表示一个函数永远不会发生值的类型
const foo = function (): never {
throw new Error();
const handler = function (message: string | number) {
switch (typeof message) {
case 'string':
break;
case 'number':
break;
default:
const check: never = message;
break;
const handler = function (message: string | number | boolean) {...};
元组 tuple
多种元素组合而成的数组
const tupleInfo: [string, number, number] = ['cqc', 1.7, 170];
type MyFunction = <T>(state: T) => [T, (newValue: T) => void];
const useState: MyFunction = function useState<T>(state: T) {
let currentState = state;
const changeState = (newState: T) => {
currentState = newState;
return [currentState, changeState];
const [counter, setCounter] = useState(10);
enum Direction {
LEFT,
RIGHT,
TOP,
BOTTOM,
function turnDirection(direction: Direction) {
switch (direction) {
case Direction.LEFT:
break;
case Direction.RIGHT:
break;
default:
break;
turnDirection(Direction.RIGHT);
enum DirectionMy {
TOP = 10,
BOTTOM = 20,
LEFT,
let d: DirectionMy = DirectionMy.TOP;
enum DirectionMy1 {
TOP = 'TOP',
泛型(重要)
const foo = function <T, S>(typeT: T, typeS: S) {
const tupleArr: [T, S] = [typeT, typeS];
return tupleArr;
interface IPerson<T1, T2 = number> {
name: T1;
age: T2;
const p: IPerson<string, number> = {
name: 'cqc',
age: 23,
class Point<T> {
x: T;
y: T;
constructor(x: T, y: T) {
this.x = x;
this.y = y;
const p = new Point('1.33', '2.22');
const p1 = new Point<string>('1.33', '2.22');
const p2: Point<string> = new Point('1.33', '2.22');
const names: Array<string> = ['cqc'];
泛型的限制
interface ILength {
length: number;
interface IMy {
name: string;
const getLength: <T extends ILength & IMy>(arg: T) => number = function (arg) {
return arg.length;
getLength({ length: 3, name: 'cqc' });
函数参数和返回值类型
function sum1(n1: number, n2: number): number {
return n1 + n2;
const names = ['cqc', 'why', 'plo'];
names.forEach((item) => {
item.length;
type AddFnType = (...args: number[]) => number;
const sum: AddFnType = (...args: number[]) => {
return args.reduce((p, c) => p + c);
sum(1, 2, 3, 1);
type PrintType = {
x: number;
y: number;
z?: number;
function printPoint(point: PrintType) {
console.log(point.x);
console.log(point.y);
console.log(point.z);
使用联合类型值时候, 需要小心该值的类型
进行很多逻辑判断(类型缩小)
返回值类型不能确定
function printID(id: number | string) {
function foo(name?: string) {}
type IDType = string | number | boolean;
类型断言 as
类型断言只允许转换为 更具体 或 不太具体的 类型, 防止不可能的强制转换
默认这种方式获取的el 类型是 HTMLElement
但是不同html标签属性不一样
这时候可以使用类型断言
const el = document.getElementById('img') as HTMLImageElement;
el.src;
class Person {}
class Student extends Person {
study() {}
function satHi(p: Person) {
(p as Student).study();
const stu = new Student();
satHi(stu);
const message = 'hello';
const num: number = message as number;
const num: number = message as unknown as number;
非空类型断言
function printMessage(message?: string) {
message!.toUpperCase();
字面量类型
字面量类型与他的值保持一致
const message: 'cqc' = 'cqc';
type Align = 'left' | 'center' | 'right';
let align: Align = 'center';
type Method = 'POST' | 'GET';
function request(url, method: Method) {}
const option = {
url: 'https:/.xxx/a',
method: 'POST' as const,
request(options.url, options.method);
?? 空值合并操作符
const a = false;
const b = 'cqc';
const res = a ?? b;
常见类型缩小方式
typeof
平等缩小 ( === , !== )
instanceof // 实例(==new 出来的==) instanceof 原型
let a = xxx;
if(typeof a === 'string') {
switch(..) {
function printTime(time: string | Date) {
if (time instanceof Date) {
time.getTime()
class Student {
studing() {}
class Teacher {
teaching() {}
function work(p: Student | Teacher) {
if (p instanceof Student) {
} else {
函数名称相同,但是参数不同的几个函数
如果可以通过联合类型实现的函数重载, 直接联合类型
感觉函数重载比较鸡肋,最终函数逻辑的实现还是在一个函数体内去判断它的参数类型,然后做相应的操作。==ts 重载的作用,只是多了一个参数校验的功能==。
type AddType = number | string;
function add(a1: number, a2: number): number;
function add(a1: string, a2: string): number;
function add(n1: any, n2: any): any {
if (typeof n1 === 'string' && typeof n2 === 'string') {
return n1.length + n2.length;
return n1 + n2;
const res = add('20', '5');
摸鱼工程师
粉丝