我有一個函式需要四個引數,其中第一個引數是必需的,第二個和第三個引數是可選的,第四個有一個默認值:
class MyClass {
static myFunc(param1: string, param2? : string, param3? : string, param4:boolean=true)
{
...
}
}
在我的呼叫者中,我想提供第一個引數的值并覆寫第四個布林值。怎么做?我做不到MyClass.myFunc("foo", false)。我應該重新設計函式簽名嗎?TypeScript 中有這樣一個功能的約定是什么?
uj5u.com熱心網友回復:
您應該重新定義函式中引數的順序和用法。
用
param?:type
通過這種方式,您可以多載函式呼叫,而無需顯式發送不必要undefined的引數。
const func = (a:number, b:boolean = true, c?:string, d?:string) => {
console.log(a, b, c, d)
}
func(1)
func(1, false)
func(1, false, "Hello")
func(1, false, "Hello", "World")
在你的情況下:
class MyClass {
static myFunc(param1:string, param2:boolean = true, param3?:string, param4?:string)
{
...
}
}
uj5u.com熱心網友回復:
以下是實作您詢問的 API 的幾種方法:
TS 游樂場鏈接
class MyClass {
// the method in your question
static myFunc (
param1: string,
param2?: string,
param3?: string,
param4 = true,
): void {
console.log([param1, param2, param3, param4]);
}
// parameters reordered
static myRefactoredFunc (
param1: string,
param4 = true,
param2?: string,
param3?: string,
): void {
console.log([param1, param2, param3, param4]);
}
}
// if you can't modify the class, you can create a function with the
// parameters ordered by your preference, which calls the original method
// in the function body and returns its return value
const myFunc = (
param1: Parameters<typeof MyClass['myFunc']>[0],
param4?: Parameters<typeof MyClass['myFunc']>[3],
param2?: Parameters<typeof MyClass['myFunc']>[1],
param3?: Parameters<typeof MyClass['myFunc']>[2],
): ReturnType<typeof MyClass['myFunc']> => MyClass.myFunc(param1, param2, param3, param4);
// these are all equivalent
MyClass.myFunc('foo', undefined, undefined, false);
MyClass.myRefactoredFunc('foo', false);
myFunc('foo', false);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/370587.html
標籤:javascript 打字稿
上一篇:insertAdjacentHTML不適用于創建的元素
下一篇:isDisplayed,isEnabled,isSelected方法在Java腳本中可用,用于selenium中的shodowdom元素
