经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » JS/JS库/框架 » JavaScript » 查看文章
常用TS总结
来源:cnblogs  作者:唯之为之  时间:2024/2/7 9:49:06  对本文有异议

自己常用的 TS 写法总结,应该会一直更新。可使用 TS在线编译 校验 TS 语法。

基本用法

普通

  1. const num: number = 10
  2. const isStop: boolean = false
  3. const title: string = '常用TS总结'
  4. const curName: null = null
  5. const curType: undefined = undefined
  6. const birthday: Date = new Date()

对象

  1. // type
  2. type LoginParams = {
  3. account: string
  4. }
  5. // interface
  6. interface LoginParams {
  7. account: string
  8. }

不确定是否有此属性用 ?

  1. interface Info {
  2. id: string
  3. name: string
  4. birthday?: Date
  5. }
  6. const curInfo: Info = { id: 'dqe2e', name: 'weizwz' }
  7. console.log(curInfo?.birthday) // undefined

数组

  1. const nums: number[] = [1, 2, 3]
  2. const answer: boolean[] = [false, true, false]
  3. const names: string[] = ['w', 'e', 'i']

对象数组

  1. interface Info {
  2. id: string
  3. }
  4. const curInfos: Info[] = [ { id: 'dqe2e' }, { id: 'der24' } ]

函数

函数需要声明参数类型和返回值类型

  1. // week: string 指参数的类型;最后的: string 指返回值类型
  2. function getWeek(week: string): string {
  3. return '星期' + week
  4. }

箭头函数

  1. const getWeek = (week: string): string => {
  2. return '星期' + week
  3. }
  4. console.log(getWeek('六')) // '星期六'

没有返回值 用 void 表示

  1. interface Cat {
  2. weight: 5
  3. }
  4. const getName = (obj: Cat): void => {
  5. console.log(obj.weight + '斤')
  6. }
  7. getName({ weight: 5 }) // '5斤'

any类型

any 类型表示没有任何限制,及时后续使用改变了类型也不会报错。但是并不推荐使用 any,否则使用 TS 也失去了意义。

  1. let x: any = 'weizwz'
  2. x = 1
  3. console.log(x) // 不报错,输出 1

真正的使用场景可能是老项目的升级,你无法确定老旧的代码具体是什么类型;或者一些特殊情况,比如接口返回值类型不确定,或者后续使用时你要修改它的类型。

  1. function getStatus(code: any): Boolean {
  2. return (code === '200' || code === 'ok' || code === 200 || code === true)
  3. }
  4. console.log(getStatus(400)) // false

类型联合 |

某个变量可能是多个类型中的一个,用 | 来分隔

  1. type Id = string | number
  2. type stringBoolean = '1' | '0'

类型交叉 &

类型交叉一般用于多个类型组成的一个新类型,用 & 来连接

  1. type Name = { name: string };
  2. type User = Name & { age: number };
  3. const zhangSan: User = { name: '张三', age: 18 }

类型断言

手动指定类型,写法是 值 as 类型<类型>值
为什么要手动指定类型,是在某些特定情况下,我们已经确定这种类型是可以这样操作,但是编译器不确定,会报错,所以我们使用类型断言去告诉编译器这样做没问题。

  1. // 我们获取到 id = name 界面元素
  2. const $name = document.getElementById("name")
  3. // 不是所有界面元素都有 value 属性,在这里我们已经确实我们拿的是 输入框元素,
  4. // 所以使用类型断言告诉编译器,如果存在这个元素,它一定是输入框元素,有 value 属性
  5. if ($name) {
  6. ($name as HTMLInputElement).value
  7. }

type 和 interface

type 命令用来定义一个类型的别名;
interface 用来声明对象结构。

区别

  • type 能表示的任何类型组合; interface 只能表示对象结构的类型
  • type 后面需要用 =;interface 后面不需要 =
  • interface 可以继承自(extends)interface 或对象结构的 type;type 可以通过 & 做对象结构的继承
  • 多次声明的同名 interface 会进行声明合并;type 不允许多次声明,一个作用域内不允许有多个同名 type

示例

type 使用

  1. type stringBoolean = '1' | '0'
  2. type Position = {
  3. x: number
  4. y: number
  5. }
  6. type Position3D = Position & { z: number }
  7. const startPosition: Position = { x: 0, y: 10 }
  8. const startPosition3D: Position3D = { x: 0, y: 10, z: 20 }
  9. // type类型不允许多次声明
  10. type Position = { z: number } // 报错,因为名为 Position 的类型已经被声明

interface 使用

  1. interface Position { x: number }
  2. interface Position { y: number }
  3. const startPosition: Position = { x: 0, y: 10 }
  4. // 同名但有相同属性,要求相同属性的类型要一致,否则会报错
  5. interface Position { x: string } // 报错,与刚开始定义的 x 类型冲突

继承扩展

  1. interface Position3D extends Position {
  2. z: number
  3. }
  4. const startPosition3D: Position3D = { x: 0, y: 10, z: 20 }

泛型

泛型一般用 T 表示,表示其中的参数/属性/返回值可以是任何类型,如果有多个泛型,可以使用其他字母。
主要使用场景:有些对象中的属性,或者方法里的参数,可能有多个类型,具体类型根据使用场景来定。

基础使用

  1. // type 这里的<T>就相当于类型入参,实际使用时传入具体类型
  2. type Empty<T> = T | undefined | null
  3. const noData: Empty<[]> = []

多个泛型

  1. interface Info<T, S> {
  2. name: string
  3. types: T[]
  4. weight: S
  5. }
  6. const tom: Info<string, number> = { name: 'tom', types: ['cat', 'animal'], weight: 5 }
  7. const idx: Info<number, string> = { name: 'idx', types: [1], weight: 'first' }

函数

  1. // 函数 <T>是泛型写法;arr: T[] 是参数类型;:T 是返回值类型
  2. function getFirst<T>(arr: T[]): T {
  3. return arr[0]
  4. }

箭头函数 <T,> 加逗号是为了避免编译程序把 <> 解析成 jsx

  1. const getFirst = <T,>(arr: T[]): T => {
  2. return arr[0]
  3. }
  4. const arr: number[] = [1, 2, 3]
  5. console.log(getFirst<number>(arr), getFirst(arr)) // <number>可省略,打印出来都是 1

嵌套

使用嵌套可以提供代码复用率,如果类型之间差别点太多就没必要了。

  1. interface Tom<T> {
  2. name: string
  3. type: T
  4. }
  5. interface People {
  6. name: string
  7. type: 'person'
  8. }
  9. interface Cat {
  10. name: string
  11. type: 'animal'
  12. }
  13. // 我的兄弟 jakeTom
  14. const myBrother: Tom<People> = {
  15. name: 'jakeTom',
  16. type: {
  17. name: 'my brother',
  18. type: 'person'
  19. }
  20. }
  21. // 我的猫咪 catTom
  22. const myCat: Tom<Cat> = {
  23. name: 'catTom',
  24. type: {
  25. name: 'cat',
  26. type: 'animal'
  27. }
  28. }

特殊用法

动态变量名

Record<Keys, Type> 返回一个对象类型,参数 Keys 用作键名,参数 Type 用作键值类型。

  1. type stringKey = Record<string, string>
  2. // 处理动态变量名
  3. const list: stringKey = { img_1: 'img/1.png', img_2: 'img/2.png', img_3: 'img/3.png' }
  4. for (const key in list) {
  5. console.log(list[key])
  6. }
  7. for(let i = 0; i < 3; i++) {
  8. console.log(list['img_' + (i + 1)])
  9. }

vue3中的TS

响应式数据

xxx.d.ts 里定义类型

  1. interface Account = {
  2. id: string
  3. name: string
  4. }

在 vue 界面里使用

  1. // 简单类型可省略类型声明
  2. const loading = ref(false)
  3. const user = ref<Account>({
  4. id: 'E2U1EU91U',
  5. name: 'weiz'
  6. })

参数传递

父组件使用

  1. <script setup lang="ts">
  2. import { ref } from 'vue'
  3. const user = ref<Account>({
  4. id: 'E2U1EU91U',
  5. name: 'weiz'
  6. })
  7. </script>
  8. <template>
  9. <Children :account="user">
  10. </template>

子组件接收参数

  1. const props = defineProps<Account>()

如果没有声明 Account,则可以具体定义

  1. const props = defineProps<{
  2. id: string
  3. name: string
  4. }>()

组件实例类型

InstanceType<T> 是 ts 自带的类型,能够直接获取组件完整的实例类型。

子组件

  1. <script setup lang="ts">
  2. const open = () => { console.log('打开')}
  3. // 子组件暴露方法
  4. defineExpose({
  5. open
  6. })
  7. </script>

父组件

  1. <script setup lang="ts">
  2. import { ref } from 'vue'
  3. import Children from './Children.vue'
  4. type ChildCtx = InstanceType<typeof Children>
  5. // 要和子组件的 ref 名称一致
  6. const childrenRef = ref<ChildCtx | null>(null)
  7. // 调用子组件方法
  8. const openChildren = () => {
  9. childrenRef.value?.open()
  10. }
  11. </script>
  12. <template>
  13. <Children ref='childrenRef'/>
  14. </template>

原文链接:https://www.cnblogs.com/weizwz/p/18009894

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号