[英]Argument of function is a property that exists in a type of Typescript
[英]typescript - detect if function exists on a type
我正在寫mocha
測試。
我有 2 個接口( TestInterface1, TestInterface2
)。 它們具有上面描述的功能,例如:
TestInterface1
- Func1, Func2
TestInterface2
- Func1, Func2, Func3
在我的測試中,我有一個 class Test
,它有時最終是TestInterface1
但可能仍然有一個 function Func3
。 這就像在運行時,無法決定它屬於哪個接口。
假設它最終成為TestInterface1
。 現在,它仍然可以有Func3
,但是由於接口,當我調用 function 時,它說 Function 不存在,即使它存在。 我怎樣才能確定Func3
仍然存在於TestInterface1
的Test
中?
// ------
// stub declaration - you have defined those interfaces already
interface TestInterface1 {
Func1: Function
Func2: Function
}
interface TestInterface2 {
Func1: Function
Func2: Function
Func3: Function
}
// assuming you have value already
declare const yourInterface: TestInterface1 | TestInterface2;
// ------
// and the IMPORTANT PART:
if ("Func3" in yourInterface) {
// in this block, yourInterface is coerced to TestInterface2
} else {
// coerced to TestInterface1
}
如果(如您的問題所述)您已經將實例的類型縮小為TestInterface1
,那么您需要斷言Func3
屬性是 function 類型才能使用它,因為編譯器不知道它存在。
您可以使用類型 predicate來執行此操作,如下面的注釋示例中所示:
// Because you didn't supply the type of your function,
// I'll provide a template for a generic one here:
type Fn<
Params extends readonly unknown[] = any[],
Result = any,
> = (...params: Params) => Result;
interface TestInterface1 {
Func1: Fn;
Func2: Fn;
}
interface TestInterface2 extends TestInterface1 {
Func3: Fn;
}
function hasFunc3 <T extends TestInterface1>(instance: T): instance is T & Pick<TestInterface2, 'Func3'> {
return typeof (instance as any).Func3 === 'function';
}
// Your question states that the instance is already narrowed to TestInterface1:
declare const instance: TestInterface1;
// Expected error:
instance.Func3(); /*
^^^^^
Property 'Func3' does not exist on type 'TestInterface1'. Did you mean 'Func1'?(2551) */
// Use the type predicate:
if (hasFunc3(instance)) {
instance.Func3(); // ok
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.