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
Using Mapped Types
You can define your mapped type using the type alias in TypeScript that can be used to specify the keys of a particular type in an object.
Syntax:
type customType = {};
Example: The below code explains the use of the mapped types to declare specific type keys in an object.
type MyObject = {
[key: string]: number;
};
const obj: MyObject = {
a: 1,
b: 2,
c: 3
};
console.log(obj);
Output:
{ a: 1, b: 2, c: 3 }
Using Interface
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 }
Using Inline Mapped Types with type
You can define a mapped type inline using the type keyword in TypeScript. This allows you to specify the keys of a particular type directly within the type declaration.
Syntax:
type TypeName = { [KeyType]: ValueType };
Example: This TypeScript code defines a type MyObject allowing string keys with number values. It creates an object obj with properties assigned numeric values and logs it.
type MyObject = { [key: string]: number };
const obj: MyObject = {
a: 1,
b: 2,
c: 3
};
console.log(obj);
Output:
{
"a": 1,
"b": 2,
"c": 3
}
Contact Us