// 声明一个 number 的特殊类型,限制参数
type numberType = 0 | 1 | 2;
function test(a:numberType = 1){
console.log(a)
}
test();
// 1
test(2);
// 2
复制代码
function test(a?: numberType):number; function test(a = 1):number | void {
console.log(a)
}
test();
// 1
test(2)
// 2
复制代码
JavaScript 模拟实现css
function test(){
if(arguments.length==0){
console.log(a)("alert!");
}
else if(arguments.length==1){
console.log(a)(arguments[0])
}
}
test();
// alert!
test(2);
// 2
复制代码
为何我会获得 Supplied parameters do not match any signature 的错误?(因为 JavaScript 没有函数重载)html
函数实现签名,它并非重载的一部分:git
function createLog(message: string): number; function createLog(source: string, message?: string): number {
return 0;
}
createLog('message'); // OK
createLog('source', 'message'); // ERROR: Supplied parameters do not match any signature
复制代码
function createLog(message: string): number;
function createLog(source: string, message: string): number;
function createLog(source: string, message?: string): number {
return 0;
}
复制代码
function isNumberType(type: number | numberType): type is numberType {
return (number as numberType) !== undedined;
}
function test(number = 1){
if(isNumberType(number)){
console.log(number)
}else{
// 咱们作更多的类型保护能够在格式错误的时候手动作一些用户提示的操做。
console.error('error number!')
}
}
test(1);
// 1
复制代码
上面的类型保护的确看起来很臃肿,不过咱们能作更多的事情。具体的类型保护官网文档讲得很清楚,你们能够再温习一下。github