Estoy escribiendo pruebas mocha
.
Tengo 2 interfaces ( TestInterface1, TestInterface2
). Tienen funciones descritas en él tales como:
TestInterface1
- Func1, Func2
TestInterface2
- Func1, Func2, Func3
En mis pruebas, tengo una clase Test
que a veces termina siendo TestInterface1
pero aún podría tener una función Func3
. Es como en tiempo de ejecución, no puede decidir a qué interfaz pertenece.
Digamos que terminó siendo TestInterface1
. Ahora, todavía podría tener Func3
, pero debido a la interfaz, cuando llamo a la función, dice que la función no existe aunque sí existe. ¿Cómo puedo darme cuenta de que Func3
todavía existe en la Test
que es de TestInterface1
?
// ------ // 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 }
Si (como se indica en su pregunta) ya ha reducido el tipo de instancia para que sea TestInterface1
, entonces deberá afirmar que la propiedad Func3
es un tipo de función para usarla, porque el compilador no lo sabe existe
Puede hacer esto usando un predicado de tipo , como en el ejemplo comentado a continuación:
// 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 }