首页 > 其他分享 >TS系列(2):类型声明、类型推断和类型总览

TS系列(2):类型声明、类型推断和类型总览

时间:2024-09-25 22:23:52浏览次数:3  
标签:string TS number let 类型 总览 type hello


你好,我是沐爸,欢迎点赞、收藏、评论和关注。

昨天分享了  TS系列(1):TS是什么?如何使用?今天咱们接着上回继续唠。

四、类型声明

使用 : 来对变量或函数形参,进行类型声明:

let a: string // 变量a只能存储字符串
let b: number // 变量b只能存储数值
let c: boolean // 变量c只能存储布尔值

a = 'hello'
a = 100 // Type 'number' is not assignable to type 'string'

b = 123
b = 'hello' // Type 'string' is not assignable to type 'number'

c = true
c = 123 // Type 'number' is not assignable to type 'boolean'

// 参数x和y必须是数字,函数返回值也必须是数字
function sum(x: number, y: number):number {
    return x + y
}

sum(1, 2)
sum(1, '2') // Argument of type 'string' is not assignable to parameter of type 'number'
sum(1, 2, 3) // Expected 2 arguments, but got 3
sum(1) // Expected 2 arguments, but got 1

: 后也可以写字面量类型,不过实际开发中用的不多

let a: 'hello' // a的值只能是字符串'hello'
let b: 100 // b的值只能是数字100

a = 'hello world' // Type '"hello world"' is not assignable to type '"hello"'
b = 200 // Type '200' is not assignable to type '100'

五、类型推断

TS 会根据我们的代码,进行类型推导,例如下面代码中的变量 a ,只能存储数字

let a = 100 // TypeScript 会推断出变量 a 的类型是数字
a = false // Type 'boolean' is not assignable to type 'number'

let obj = {
    name: 'xiaoming',
    age: 6
}
obj.name = null // Type 'null' is not assignable to type 'string'
obj.age = '8' // Type 'string' is not assignable to type 'number'

但要注意,类型推断不是万能的,面对复杂类型时推断容易出问题,所以最好明确类型声明!

六、类型总览

JavaScript 中的数据类型

  1. string
  2. number
  3. boolean
  4. null
  5. undefined
  6. bigint
  7. symbol
  8. object

备注:其中 object 包含:Array、Function、Date、Error 等......

TypeScript 中的数据类型

  1. 上述所有 JavaScript 类型
  2. 六个新类型
    • any
    • unknown
    • never
    • void
    • tuple
    • enum
  1. 两个用于自定义类型的方式:
    • type
    • interface

注意点

在 JavaScript 中的这些内置构造函数:NumberStringBoolean,它们用于创建对应的包装类型,在日常开发时很少使用,在 TypeScript 中也是同理,所以在 TypeScript 中进行类型声明时,通常都是用小写的 numberstringboolean

例如下面的代码:

let str1: string
str1 = 'hello'
str1 = new String('hello world') // Type 'String' is not assignable to type 'string'. 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible.

let str2: String
str2 = 'hello' // 不会报错
str2 = new String('hello world') // 不会报错

1.原始类型 VS 包装类型

  • 原始类型:如 numberstringboolean,在 JavaScript 中是简单数据类型,它们在内存中占用空间少,处理速度快。
  • 包装类型:如 Number 对象、String对象、Boolean对象,是复杂类型,在内存中占用更多空间,在日常开发中很少由开发人员创建包装对象。

2.自动装箱:JavaScript 在必要时会自动将原始类型包装成对象,以便调用方法或访问属性。

自动装箱示例代码:

// 原始类型字符串
let str = 'hello'

// 当访问 str.length 时,JavaScript 引擎做了以下工作:
let size = (function() {
    // 1.自动装箱:创建一个临时的 String 对象包装原始字符串
    let temStringObject = new String(str)

    // 2.访问 String 对象的 length 属性
    let lengthValue = temStringObject.length

    // 3.销毁临时对象,返回长度值
    return lengthValue
})()

console.log(size) // 5

好了,分享结束,谢谢点赞,下期再见。

标签:string,TS,number,let,类型,总览,type,hello
From: https://blog.csdn.net/m0_37943716/article/details/142533719

相关文章

  • 0924-25,QT的数据类型,实现一个井字棋和计算器(只输入)
    day-01#include"mainwindow.h"#include<stdio.h>#include<iostream>#include<QApplication>#include<QDebug>#include<QPoint>#include<QLine>intmain(intargc,char*argv[]){QApplicationa(argc,......
  • Go从入门到放弃之数据类型
    数据类型概述Go支持的数据类型基本数据类型布尔类型:bool整型:int8、byte、int16、int、uint、uintptr等浮点类型:float32、float64复数类型:complex64、complex128字符串:string字符类型:rune错误类型:error复合类型指针(pointer)数组(arr......
  • 选错屏幕类型,护眼可能成空谈——类纸护眼屏与墨水屏有什么区别?
    类纸护眼屏与墨水屏是两种不同的显示技术,它们在显示原理、视觉体验和应用场景上有所区别。以下是对这两种技术的对比分析:特性类纸护眼屏墨水屏(电子墨水屏)显示原理通常采用液晶显示技术,通过特殊的AG防眩光、圆偏光等技术处理,模拟纸张的显示效果利用电场作用下电子墨水粒子的运......
  • Rust字符串类型全解析
    字符串是每种编程语言都绕不开的类型,不过,在Rust中,你会看到远比其他语言更加丰富多样的字符串类型。如下图:为什么Rust中需要这么多种表示字符串的类型呢?初学Rust时,可能无法理解为什么要这样设计?为什么要给使用字符串带来这么多不必要的复杂性?其实,Rust中对于字符串的设计,优先......
  • 【2024潇湘夜雨】WIN 11_IoT_Ent_LTSC_2024_24H2.26100.1876软件选装纯净特别版9.25
    【系统简介】=============================================================1.本次更新母盘来自WIN11_IoT_Ent_LTSC_2024_24H2.26100.1876.2.全程离线精简、无人值守调用优化处理制作。部分优化适配系统可能要重启几次,即使显示适配失败也不要在意,可能部分优化不适用。3.OS版本号......
  • pyecharts库简单使用
    官网https://pyecharts.org/#/zh-cn/简单使用frompyecharts.chartsimportLine#创建折线图对象line=Line()#折线图x轴添加数据line.add_xaxis(["小明","小红","小强"])#折线图y轴添加数据line.add_yaxis("体重",[60,45,70])#生成图表的htmlline.render(......
  • CS1112 Specific programming constructs
    CS1112Fall2024Project2dueWednesday9/25at11pmObjectivesCompletingthisprojectwillsolidifyyourunderstandingoffor-loops,while-loops,andnestedloops.Thecomputationalthemeofthisprojectissimulation,withproblem1usingrandomnessa......
  • Understanding the difference between a Java keystore and a truststore
    Atruststoreisafilethatcontainsoneormorepubliccertificates,butnoprivatekeys. Akeystoreisafilethatcontainsoneormorepubliccertificatesandoneormoreprivatekeys.Thisistypicallya"chain"wherethekeystorecontain......
  • Server-Sent Events (SSE) Koa2 & Nginx & React 实践
    Server-SentEvents(SSE)Koa2&Nginx&React实践得鹿梦鱼前端+node全栈,骑马找马中,有兴趣可私聊​关注他 在现代Web应用中,实时数据传输变得越来越重要。Server-SentEvents(SSE)是一种轻量级的技术,允许服务器向客户端主动发送更新。本文将详细介......
  • fetchEventSource使用+源码解析
    fetchEventSource使用+源码解析nonhana杭电大三学生,喜欢搞前端。​关注他创作声明:包含AI辅助创作12人赞同了该文章前言最近由于一些乱七八糟的原因,接触到了国内开发的一些类ChatGPT的API的前端调用与功能集成。概括的来说,就是有一......