TS 报错

150 阅读2分钟

ts 定义方法参数变量是否必传

不能将类型“(init?: boolean) => void”分配给类型“(evt: MouseEvent) => any”。  
参数“init”和“evt” 的类型不兼容。

image.png

1.在seach(val = true)参数加默认值 2.seach(true) 带参数

应有 2 个参数,但获得 1 个。

image.png

? 可传可不传

const addOrEdit = (which: string, row?: AddOrEditRuleForm | undefined): void => {

表单提交不需要写返回值?

image.png

Promise<boolean | undefined>

image.png

但这样写为啥不会报错???

接口返回值 res 定义any 参数“res”隐式具有“any”类型

image.png

直接加res:any

元素隐式具有 "any" 类型,因为类型为 "string | number | symbol"

尝试了很多方法没有解决,最后在tsconfig.json文件添加了配置

"suppressImplicitAnyIndexErrors": true,

blog.csdn.net/m0_47670683…

blog.csdn.net/qq_40681984…

定义type不行

image.png

image.png

但是写成这种定义的又可以

image.png

console.log(popupTypes[popupViewType]); // error 元素隐式具有 "any" 类型,因为类型为 "string" 的表达式不能用于索引类型

//这样就好了
let aaa = popupTypes[popupViewType as keyof typeof popupTypes];
console.log(aaa);// aaa

类型“string | number | object[]”上不存在属性“push”。 类型“string”上不存在属性“push”

单个表单需要校验 需要加个判断

image.png

vue3 ts 导出组件提示 (no)

import UploadImage from '@/components/uploadImage/uploadImage.vue';

image.png www.jianshu.com/p/501e9b45d…

image.png

type ComponentInternalInstance = /unresolved/ any (no)

image.png

定义对象数组 (对象为接口interface)

interface Config {
  name: string;
  value: string;
  icon: string;
  occupancy?: number;
  detail?: string;
}


//const configs: Config[] =[]

 const configs: Config[] = reactive([
    {
      name: '内存',
      value: '',
      icon: memoryIcon,
    },
    {
      name: 'CPU',
      value: '',
      icon: cpuIcon,
    },
    {
      name: 'GPU',
      value: '',
      icon: gpuIcon,
    },
    {
      name: '数据盘硬盘使用量',
      value: '',
      occupancy: 0,
      icon: diskIcon,
    },
  ]);


可选参数必须放下必选参数后面

image.png

定义数组类型

blog.csdn.net/m0_46550764…

类型+方括号定义。
数组泛型:Array<类型>
接口表示数组:数组的本质是对象,定义index为number即可。

interface NumberArray {
    [index: number]: number;
}
let fn: NumberArray = [1, 1, 2, 3, 5];


该定义方法多存在于类数组中,如函数的arguments,就是类数组,可以使用数组的length、使用下标获取到项,但是却无法使用任何数组的方法,如arr.sort(),且其本身有一个属性callee,指向当前的函数。此时就需要使用接口来定义。

interface IArgs{
[index: number]: number;
        length: number;
        callee: Function;
}
function sum() {
    let args: IArgs = arguments;
}

ts 如何定义forEach里面的item?

image.png