必填参
参数一旦声明,就要求传递,且类型需符合,
function greeting(person: string): string {return "Hello, " + person;}greeting('tom')
可选参数
参数名后面加上问号,变成可选参数,
function greeting(person: string, msg?: string): string {return "Hello, " + person;}greeting('tom')greeting('tom', 'glad to see you')
默认值
跟可选参数相似,但是不传参时,会使用默认的参数,
function greeting(person: string, msg = ""): string {return "Hello, " + person;}greeting("tom");greeting("tom", "glad to see you");
函数重载
以参数数量或类型区分多个同名函数,
// 重载1function watch(cb1: () => void): void;// 重载2function watch(cb1: () => void, cb2: (v1: any, v2: any) => void): void;// 实现function watch(cb1: () => void, cb2?: (v1: any, v2: any) => void) {if (cb1 && cb2) {console.log("执行watch重载2");} else {console.log("执行watch重载1");}}// 执行watch重载1watch((): void => {console.log(123);});// 执行watch重载2watch((): void => {console.log(123);},(): void => {console.log(321);});
<template><div><input type="text" placeholder="输入新特性" @keyup.enter="addFeature" /></div></template><script lang="ts">import { Component, Vue } from "vue-property-decorator";@Componentexport default class HelloWorld extends Vue {addFeature(e: KeyboardEvent) {const target = e.target as HTMLInputElement;console.log(target.value);}}</script>
