Reputation: 46960
I'm trying to implement a method like that takes a key argument that is either a string
or an instance of the indexable type interface IValidationContextIndex
. The implementation looks like this:
/**
* Gets all ValidationContext container values.
* @returns An array of ValidationContext instances contained in the cache.
*/
public static getValidationContextValues(key: IValidationContextIndex | string ): Array<ValidationContext> {
if (key instanceof IValidationContextIndex ) [
return Object.values(<any> key);
]
else {
const vci = ValidationContainer.cache[<string>key];
return Object.values(<any> vci);
}
}
Typescript give the following error for the if
block:
[ts] 'IValidationContextIndex' only refers to a type, but is being used as a value here.
Any ideas on how to fix this?
For most interface I think it's possible to add a type
property ( type: 'IValidationContextsIndex'
;
), but that does not work in this case since the the interface is an indexable type interface ....
Upvotes: 3
Views: 1069
Reputation: 46960
I think this will do it (Per the tip from @indrakumara):
/**
* Gets all ValidationContext container values fpr a
* Object_property string valued key or a key that is an instance of
* IValidationContextIndex).
* @returns An array of ValidationContext instances contained in the cache that corresponds to a specific Object_property key.
*/
public static getValidationContextValues(key: any ): Array<ValidationContext> {
if (typeof key === `string` ) {
const vci = ValidationContainer.cache[<string>key];
return Object.values(<any> vci);
}
else {
return Object.values(<IValidationContextIndex> key);
}
}
Upvotes: 2
Reputation: 660
Interfaces in typescript doesn't transpile into any code in javascript. So in your code, "instanceof IValidationContextIndex", IValidationContextIndex doesn't exist in javascript.
Change your interface to class or have a class implementing the interface and then check if passed parameter is instanceof that class.
Upvotes: 1
Reputation: 3911
There isnt a way to check the type in typescript at run time as almost everything becomes an object once transpiled, so you may have to something along what is defined as user-defined typed guards
Upvotes: 2