TS系列之typeof

TS系列之typeof

前言

今天总结一下typeof相关的知识。
typeof在Js中也是常用来判断变量类型的关键字,那么在Ts中的作用又是什么,下面一起来看看。

回顾:Js中typeof的用法

1、typeof的返回类型有哪些

  • “undefined”
 typeof undefined
  • “object”
 typeof null
 或者其他任意对象

至于null为什么返回的类型是object可以参考这篇文章:typeof null is ‘object’

  • “boolean”
typeof true
  • “number”
typeof 1
  • “bigint”
 typeof BigInt(1)
  • “string”
 typeof ""
  • “symbol”
 typeof Symbol(1)
  • “function”
 typeof function a () {}

Ts 中的 typeof 运算符作为类型判断的工具

什么是 typeof?

typeof 是 TypeScript 中的运算符,用于获取给定表达式的类型。返回一个表达式类型的字符串。

一个简单的例子:

const num = 1;
const str = "Hello";
console.log(typeof num); // 输出 "number"
console.log(typeof str); // 输出 "string"

在这个例子中,typeof num 返回 “number”,而 typeof str 返回 “string”,很明显这和js中没有什么区别。

类型保护与条件类型

typeof 运算符的真正强大之处在于它与条件类型的结合使用。通过将 typeof 与条件类型结合,我们可以在运行时对不同类型的代码进行条件分支。
举个例子:
比如我们想要实现一个函数,将传入的数字或者字符串类型的数据自增1并返回

function test (num: number | string): number | string {
  return num++
}
//这时候ts报错,提示:An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type.
//意思是:算术操作数的类型必须是“any”、“number”、“bigint”或枚举类型

这个时候typeof就可以派上用场,改造如下:

function test (num: number | string): number | string {
  if (typeof num === 'number') {
    return ++num;
  } else {
    return +num + 1;
  }
}

复杂类型

typeof 判断复杂类型时和js中的用法一样"object"、“function”、“symbol” 等等。
接下来我们看一下实际在开发中用的场景:
1、例如我们有个对象,如果对象嵌套深或者对象属性较多时,那么你就可以直接用tyoeof来获取这个对象的属性中的所有类型。

const appconfig = {
  id: '1',
  text: 'app',
  appName: 'app',
  appImg: 'https://app',
  appType: 'app',
  positionNum: 1,
  url: 'https://app'
}

type appType = typeof appconfig
type appType = {
    id: string;
    text: string;
    appName: string;
    appImg: string;
    appType: string;
    positionNum: number;
    url: string;
}
const appconfigtest: appType = {}
//所以你就可以直接用appType来约束新定义对象appconfigtest

2、也可以获取对象中单个属性的类型

type appType = typeof appconfig.appImg
//type appType = string

3、当我想要通过函数创建并获取类的实例,那么就可以通过typeof获取到class构造函数的类型

class APP {
  name: string;
  img: string;
  constructor (name: string, img: string) {
    this.name = name;
    this.img = img;
  }
}
//(parameter) CP: new (name: string, img: string) => APP
function createApp(CP: typeof APP, name: string, img: string) {
  return new CP(name, img);
}

总结

到这里我们就基本了解了typeof在ts中常见的一些用法, 其它用法还需继续探索,分享学习。

### 解决 npm ERR! ERESOLVE 错误 `npm ERR! ERESOLVE could not resolve` 是由于依赖冲突或版本不兼容引起的常见问题。以下是几种可能的原因及其解决方案[^4]: 1. **存在重复的依赖项**: 当多个包请求同一软件的不同版本时会发生这种情况。可以尝试使用 `npm dedupe` 命令来解决这个问题,它会自动寻找机会合并那些可以安全共享的相同版本。 2. **特定范围内的版本号过旧或者太新**: 如果 package.json 文件中的某些依赖指定了非常具体的版本约束(如 ^ 或 ~),这可能会阻止找到合适的候选者。考虑放宽这些条件至更宽泛的形式,例如只写主要版本号而不带次要和修订部分。 3. **缓存损坏**: 有时候本地存储的数据可能出现异常情况从而引发此类报错消息。执行命令清除现有缓存后再重试安装过程:`npm cache clean --force`. 另外值得注意的是,从 npm v7 开始,默认行为已改变为严格模式解析引擎,这意味着即使间接依赖之间存在差异也会抛出错误而不是警告。如果你希望恢复以前的行为可以在全局范围内设置偏好参数: ```bash npm set legacy-peer-deps true ``` 之后再重新运行原来的安装指令应该就能绕过大部分因 peerDependency 导致的问题了[^5]。 --- ### 优化 Vue3、TypeScriptTSX 封装组件的依赖配置 根据前次讨论的内容可知,在构建支持 TypeScript 类型定义文件 (.d.ts) 的 Vue 组件库过程中,确实有必要引入像 `vite-plugin-dts` 这样的工具辅助完成自动化流程工作。然而并非所有列举出来的 devDependencies 都不可或缺,具体可以根据实际应用场景做适当删减: - 对于纯前端项目而言,“@types/react” 及其关联 DOM 扩展显然多余; - 同样道理,“rollup”系列相关插件假如整个工程架构已经切换到了 Vite 上面的话也是多余的负担; - 关于样式处理方面,除非特别强调 CSS Modules 功能否则常规情况下 “postcss” 插件亦可省略; 经过筛选后的推荐基础版 dependencies 列表如下所示: ```json { "dependencies": { "@ace-util/core": "^0.3.1", "vue": "^3.x.x" }, "devDependencies": { "typescript": "~latest", "vite": "^4.x.x", "vitest": "^0.x.x", "eslint": "^8.x.x", "prettier": "^2.x.x", "vite-plugin-dts": "^2.x.x", "@vitejs/plugin-vue": "^4.x.x" } } ``` 此外还需注意调整 tsconfig.json 设置以适应最新改动后的生态系统环境要求[^6]。 --- ### 实现代码片段 这里给出一个简单的例子用来演示如何创建带有完整类型信息支持的自定义按钮组件: ```tsx <script lang="tsx"> import { defineComponent } from 'vue' type ButtonSize = 'small'|'medium'|'large'; interface IButtonProps { label:string; size?:ButtonSize; onClick?:(event:Event)=>void; } export default defineComponent({ name:"CustomButton", props:{ label:{required:true,type:String}, size:{default:'medium',type:[String]}, onClick:{type:Function as ()=>(event:Event)=>void} }as PropOptions<IButtonProps>, emits:['click'], setup(props,{emit}){ function handleClick(event:Event):void{ emit('click',event); if(typeof props.onClick === 'function')props.onClick(event); } return ()=>{ const classes=`btn btn-${props.size}`; return( <button class={classes} onClick={(e:Event)=>handleClick(e)}>{props.label}</button> ) } } }) </script> <style scoped> .btn{padding:.5em 1em;border-radius:.25em;} .btn-small{font-size:.8rem;} .btn-medium{font-size:1rem;} .btn-large{font-size:1.2rem;} </style> ``` 上面这段代码展示了如何结合 TypeScript 接口定义与 JSX 表达式共同打造具备良好用户体验反馈机制的基础交互控件实例[^7]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值