Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
How To Pick And Omit Keys in TypeScript?
Next article icon

How to Declare Specific Type of Keys in an Object in TypeScript ?

Last Updated : 20 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 Record Utility 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.

JavaScript
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 an 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 the interface.

Interface interfaceName{}

Example: The below code example explains the use of the interface to declare specific type of keys in an object.

JavaScript
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.

JavaScript
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 Record Utility Type

TypeScript provides utility types that help in creating complex types from existing ones. These can be particularly useful for specifying specific key types in an object.

Example: The Record utility type is used to construct an object type with specified keys and a uniform value type.

JavaScript
// Define a type with specific keys of a certain type type MyObject = Record<'name' | 'age' | 'email', string>;  // Create an object conforming to the specified type const obj: MyObject = {     name: "Nikunj",     age: "22",     email: "[email protected]" };  console.log(obj); 

Output
{ name: 'Nikunj', age: '22', email: '[email protected]' } 

In this article, we explored different methods to define specific key-value types in TypeScript using index signatures. We covered using mapped types, interfaces, and inline mapped types with the type keyword. Each method allows for flexible and robust object type definitions, ensuring type safety and consistency within your TypeScript code.


Next Article
How To Pick And Omit Keys in TypeScript?

G

geekwriter2024
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • TypeScript

Similar Reads

  • How to Check the Type of an Object in Typescript ?
    When working with TypeScript, understanding how to check the type of an object is crucial for ensuring type safety and maintaining code integrity. TypeScript, being a statically typed superset of JavaScript, provides several approaches to accomplish this task as listed below. Table of Content Using
    3 min read
  • How to Filter Keys of Type string[] in TypeScript ?
    In TypeScript, the filtering of keys of type string[] can be done by iterating over the data object, and applying the condition to the string if the key is a string. If the condition is satisfied, then an array of output results is created which consists of filtered keys of type string[]. The below
    3 min read
  • How To Pick And Omit Keys in TypeScript?
    In TypeScript, when working with objects, there are scenarios where we may want to pick or omit certain keys from an existing type. TypeScript provides utility types Pick and Omit to accomplish this. These utilities allow us to create new types by including or excluding specific properties from an e
    4 min read
  • How to Sort or Reduce an Object by Key in TypeScript ?
    Sorting an object by key generally refers to arranging its properties in a specific order, while reducing involves selecting a subset of properties based on provided keys. Different approaches allow developers to perform these operations with flexibility. Below are the approaches used to sort or red
    3 min read
  • How to declare nullable type in TypeScript ?
    In vanilla JavaScript, there are two primary data types: null and undefined. While TypeScript previously did not allow explicit naming of these types, you can now use them regardless of the type-checking mode. To assign undefined to any property, you need to turn off the --strictNullChecks flag. How
    2 min read
  • How to Declare Object Value Type Without Declaring Key Type in TypeScript ?
    We will create an object value type without declaring the key type. We can not directly define the type of value we will use different methods for declaring the object value type. These are the following methods for declaring the object value type: Table of Content Using Record Utility TypeUsing Map
    4 min read
  • How to Specify that a Class Property is an Integer in TypeScript ?
    Specifying that a class property is an integer in TypeScript involves using type annotations or specific TypeScript features to define the data type of the property. Below are the approaches used to specify that a class property is an integer in TypeScript: Table of Content By using Type AnnotationB
    2 min read
  • How to Create a Typed Array from an Object with Keys in TypeScript?
    Creating a typed array from the keys of an object in TypeScript ensures that your application maintains type safety, particularly when interacting with object properties. Here we'll explore different approaches to achieve this using TypeScript's built-in Object methods. Below are the approaches used
    3 min read
  • How to Create an Object in TypeScript?
    TypeScript object is a collection of key-value pairs, where keys are strings and values can be any data type. Objects in TypeScript can store various types, including primitives, arrays, and functions, providing a structured way to organize and manipulate data. Creating Objects in TypescriptNow, let
    4 min read
  • How to Convert an Array of Objects into Object in TypeScript ?
    Converting an array of objects into a single object is a common task in JavaScript and TypeScript programming, especially when you want to restructure data for easier access. In this article, we will see how to convert an array of objects into objects in TypeScript. We are given an array of objects
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences