If I have for example this super simple interface:
interface Dog {
name: string;
}
Is there any way to check the type of the key? As for example, we do this easily with a normal var:
let hi: number = 2;
if(typeof hi === 'number') { // It's possible
console.log('yes, it is');
}
if(typeof Dog['name'] === 'string') { // It's not possible
console.log('yes, it is');
}
The error: 'Dog' only refers to a type, but is being used as a value here.
Any suggestion?
CodePudding user response:
Interfaces in TypeScript are purely a compile time construct and don't persist at runtime. Thus you cannot do typechecks on that compile time construct.
The typeof
operator in JavaScript does not have anything to do with the types you defined in TypeScript but does a runtime check. To use it that way (like with typeof hi === 'number'
, you'd have to have an object of type dog:
interface Dog {
name: string;
}
const x: Dog = { name: 'Duke' };
if (typeof x['name'] === 'string') {
console.log('yes, it is');
}
This however would not bring much benefit in this particular case since TypeScript will already ensure that the name is a string so the condition will always be true.
CodePudding user response:
This requires runtime type meta-information which doesn't exist in TypeScript. TypeScript transpiles to JavaScript and JavaScript doesn't have metadata on types such as field type info in a class.
So my answer is, it is not possible to do what you are asking for directly.
All the sophisticated typing that you experience in TypeScript exists only during development.