typecript在vue3中的使用(一)

130 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第1天,点击查看活动详情

1. 原始数据类型、任意值、内置对象、数组的类型、接口类型、函数的类型

  • 在.ts文件中的使用
# 原始数据类型,布尔值、数值、字符串、nullundefinedsymbolbigint;
# 例如:
    const row:number = 1;
    const flag:boolean = false;
    const key:string = 'no'
    const value:undefined = undefined

# 任意值,any
# 例如:
    const data:any;

# 内置对象,
# 如:`Boolean``Error``Date``RegExp` 等;
# 如:`Document``HTMLElement``Event``NodeList` 等
# 例如:
    const dom = document.querySelector('body') as HTMLElement;
    dom.addEventListener('click', function(e:Event) {
        console.log(e.targetCurrent);
    });

# 数组的类型
# 例如:
    let indexArr: number[] = [];
    let codes:string[] = [];

# 接口的类型
# 例如:
# 示例1
    export interface ruleItemI{
      min:number|string,
      data?:number[],
      unit:string,
      default?:number|string,
      [propName:string]:any
    }
    const defaultValue:ruleItemI = {
        min:'',
        unit:'',
        symbol:'',
        default:'',
        step:'',
    }
# 示例2
    interface typeI{
      push():void,
      pop():void,
      radio():void
    }
    type EventNames = 'push'|'pop'|'radio';//此处为字符串字面量类型
    function doIt(type:EventNames='push'){
        let obj:typeI = {//选中
          push(){
              console.log('push')
          },
          pop(){//不选中或删除
            console.log('pop')
          },
          radio(){//单选
            console.log('radio')
          }
        }
        obj[type as EventNames]()
    }
# 函数的类型
# 例如:
    function getInfo(name:string,age:number,isMan:boolean,result?:string){
        console.log(`${name}是?${isMan?'男':'女'},年龄为${age},现状是${result??'未知'}`);
    }
    getInfo('leo',2,true,undefined)

    function getData(list:string[]):string{
        return list.join(',')
    }
    getData(['leo','wang','Mela'])

    function getData(string:string):string[]{
        return list.split(',')
    }
    getData('leo,wang,Mela')
  • 在vue3中的使用
# 原始数据类型
<script setup lang="ts">
    import {ref,watch,computed,reactive} from 'vue'
    const row = ref<number>(1);
    const flag = ref<boolean>(false);
    const key = ref<string>('no');
    const emits = defineEmits(['update:modelValue'])
    const modelValueSet = computed({
        get():string{
          return modelValue.value
        },
        set(value:string){
          emits('update:modelValue',value)
        }
    })
    watch(()=>flag.value,(newVal:boolean)=>{
        console.log(newVal,'==============1')
        data.value = newVal
    })
    watch(key,(newVal:string)=>{
        console.log(newVal,'==============1')
        data.value = newVal
    })

# 任意值
    const treeRef = ref<any>(null);//对应组件的ref='treeRef'

# 内置对象,
# 如:`Boolean``Error``Date``RegExp` 等;
# 如:`Document``HTMLElement``Event``NodeList` 等
# 例如:
    # template
    <el-button @click="handleCopy($event)" class="ml10" type="primary" plain>复制</el-button>
    # script
    const handleCopy = (e:Event)=>{
        const target = e.target as HTMLElement;
        console.log(target)
    }
# 数组的类型
# 例如:
    const nameArr:string[] = reactive(['leo']);
    const list = ref<any[]>([]);

# 接口的类型
# 例如:
    interface formObjectI{
        no:string,
        name:string,
        parentMenuNo:string,
        parentApplicationNo:string
    }
    const formObject: formObjectI = reactive({ no: '', name: '', parentMenuNo: '',  parentApplicationNo: ''})

</script>

2. 类型推论、类型断言、类型别名

  • 在.ts文件中的使用
#类型推论
    const name = 'leo';//name为string类型

# 类型断言
    const target = e.target as HTMLElement;
  • 在vue3中的使用
# 类型推论
    const age = ref(10);
# 类型断言
    import { PropType } from 'vue'
     const props = defineProps({
        data: { //
          type: Array as PropType < string[] > ,
          default () {
            return []
          }
        },
     })

# 类型别名
    type getInfoType = ()=>string;
    type infoType = string;
    type infoTypeAll = getInfoType|infoType
    function getInfo(info: infoTypeAll) {
        if (typeof info === 'string') {
            console.log(info)
        } else {
            console.log(info())
        }
    }
    getInfo('lea')

3. 字符串字面量类型、元祖、枚举

# 字符串字面量类型
type configTypeT = '1'|'2'|'3';//选项:1;答案:2;范围:3
type EventNames = 'push'|'pop'|'radio';

# 元祖【合并了不同类型的对象】
let tom: [string, number] = ['Tom', 25];

# 枚举