How to use Interface In Typescript
You can also use a interface to define your custom type where the keys of the object are typed to a specific type and can later be used to type interface.
Syntax:
Interface interfaceName{}
Example: The below code example explains the use of the interface to declare specific type of keys in an object.
interface MyObject {
[key: string]: number;
}
const obj: MyObject = {
a: 1,
b: 2,
c: 3
};
console.log(obj);
Output:
{ a: 1, b: 2, c: 3 }
How to Declare Specific Type of Keys in an Object in TypeScript ?
In TypeScript, object definitions can include specific key-value types using index signatures. You can declare specific types of keys in an object by using different methods as listed below:
Table of Content
- Using Mapped Types
- Using Interface
- Using Inline Mapped Types with type