Introduction to TypeScript Object Type
TypeScript object type is a type of any non-primitive values. TypeScript has introduced a new type called an object with version 2.2. It represents all non-primitive types. TypeScript is a superset of statically typed JavaScript, including static language typing. In TypeScript, the Object Type defines an object’s shape or structure, enabling the specification of properties and types an object should possess.
It is a commonly employed type for representing non-primitive values like numbers, strings, Booleans, null, undefined symbols, etc. Unlike primitive values, non-primitive ones store references or addresses to the memory location where the data is stored. Consequently, when working with non-primitive values, one typically interacts with references to the data rather than the data itself. Non-primitive values often show mutability, meaning their state can change after creation. In version 2.2, the TypeScript team introduced the TypeScript object.
Table of Contents:
Basic Syntax of Object Type in TypeScript
// Define an object type with specific properties and their types
type MyObjectType = {
propertyName1: type1;
propertyName2: type2;
// ... additional properties
};
Where,
- type MyObjectType: Declares a new type named MyObjectType
- { }: Inside the curly braces, you define the properties of the object type along with their respective types.
- propertyName: type;: It specifies that the MyObjectType must have a property named propertyName1 of type type1. Similarly, you can add multiple properties as well.
Examples of TypeScript Object Type
Given below are the examples of TypeScript Object Type:
Example 1: Basic
let student: {
name: string;
rollNo: number;
age: number;
standard: string;
};
student = {
name: 'Karthik',
rollNo: 25,
age: 12,
standard: '6B'
};
console.log(`Here are the details of Student with Roll. ${student.rollNo}`, student);
Output:
Explanation:
First, we declare a variable named student. The type is an inline type declaration specifying that student should be an object with the following properties:
- name: a string
- rollNo: a number
- age: a number
- standard: a string.
Then, the program assigns an object to the student variable. The object has values for each property specified in the type declaration. This object represents a student with a name (‘Karthik’), roll number (25), age (12), and standard (‘6B’).
Finally, the program uses a console.log statement to print details about the student.
TypeScript objects such as student in the above example have a fixed list of properties. Hence, if the user tries to access a property that does not exist with the object student, we will get an error: ‘Property “X” does not exist on type ‘student.’
Example 2: With an interface
An interface is a way to specify the structure of an object.
Code:
interface Person {
name: string;
age: number;
gender: string;
}
let person1: Person = {
name: "John",
age: 30,
gender: "Male",
};
let person2: Person = {
name: "Jane",
age: 25,
gender: "Female",
};
function greet(person: Person): string {
return `Hello, ${person.name}!`;
}
console.log(greet(person1));
console.log(greet(person2));
Output:
Example 3: Using an alias
An alias is a feature that allows you to create a new name for a type. Aliases are handy for simplifying complex type definitions, improving code readability, and facilitating code maintenance.
Code:
type Book = {
title: string;
author: string;
publicationYear: number;
genre: string;
};
let myBook: Book = {
title: "The Catcher in the Rye",
author: "J.D. Salinger",
publicationYear: 1951,
genre: "Fiction",
};
function displayBookInfo(book: Book): string {
return `Title: ${book.title}\nAuthor: ${book.author}\nYear: ${book.publicationYear}\nGenre: ${book.genre}`;
}
console.log(displayBookInfo(myBook));
Output:
Explanation:
In the above code, we define a type alias Book. It specifies that an object of type Book should have four properties: title (a string), author (a string), publicationYear (a number), and genre (a string).
Then, an object named myBook is declared, adhering to the structure defined by the Book type. It represents a book with specific details: title, author, publication year, and genre.
Then, the function displayBookInfo takes a parameter book of type Book and returns a string. Inside the function, we use a template string to construct a formatted string containing information about the book., including its title, author, publication year, and genre.
Lastly, The program calls the displayBookInfo function with myBook as an argument, and The program logs the resulting string to the console. This line outputs information about the book represented by myBook.
Example 4: Optional properties
The optional properties allow us to define properties in an object type that may or may not be present when creating an instance of that type. To denote optional properties, you add a ‘?‘ after the property name.
Code:
type Movie = {
title: string;
director: string;
releaseYear: number;
genre?: string;
rating?: number;
};
let myMovie: Movie = {
title: "Inception",
director: "Christopher Nolan",
releaseYear: 2010,
rating: 8.8,
};
function displayMovieInfo(movie: Movie): string {
const genreInfo = movie.genre ? `\nGenre: ${movie.genre}` : '';
const ratingInfo = movie.rating ? `\nRating: ${movie.rating}` : '';
return `Title: ${movie.title}\nDirector: ${movie.director}\nYear: ${movie.releaseYear}${genreInfo}${ratingInfo}`;
}
console.log(displayMovieInfo(myMovie));
Output:
Example 5: read-only property
Read-only properties are properties of an object that you can only assign a value to during the object’s initialization or within the object’s constructor. Once you assign a value to a read-only property, you cannot change or reassign it. This feature helps enforce immutability for specific properties within an object.
Code:
interface Configuration {
readonly apiKey: string;
endpoint: string;
}
function processConfiguration(config: Configuration) {
console.log(`API Key: ${config.apiKey}`);
console.log(`Endpoint: ${config.endpoint}`);
config.endpoint = "https://new-endpoint.com";
config.apiKey = "new-api-key";
}
const initialConfig: Configuration = {
apiKey: "abc123",
endpoint: "https://api.example.com",
};
processConfiguration(initialConfig);
Output:
Example 6: empty objects
An empty object refers to an object lacking any defined properties. Essentially, it’s an object literally devoid of any key-value pairs.
Code:
// Function that returns an empty object
function getEmptyObject(): {} {
return {};
}
// Variable of type {}
let emptyObject: {} = {};
// Object with type annotation {}
let anotherEmptyObject: {} = {
// No properties
};
// Function that accepts an empty object as a parameter
function logEmptyObject(obj: {}): void {
console.log(obj);
}
// Calling the function with an empty object
logEmptyObject({});
Output:
Example 7: any type
Any type is a special type that represents a value of any type. When you assign a variable to any type, it tells the TypeScript compiler to suspend static type checking for that particular variable. This means you can assign values of any type to a variable of type any, and TypeScript won’t raise type-related errors.
Code:
let anyValue: any;
// Assigning different types of values to the 'any' variable
anyValue = 5; // number
anyValue = 'hello'; // string
anyValue = true; // boolean
anyValue = [1, 2, 3]; // array
anyValue = { key: 'value' }; // object
// You can call any method or access any property without type checking
let lengthOfAnyValue: number = anyValue.length; // No error, even if 'length' doesn't exist on some types
// 'any' allows mixing different types without type-checking
let mixedArray: any[] = [1, 'two', true];
// You can even perform unsafe operations
let unsafeValue: any = 'This is a string';
let unsafeLength: number = unsafeValue.length; // No error, even if 'length' is not applicable to a string
Object VS object in TypeScript
The uppercase Object refers to the built-in JavaScript Object constructor function, which creates and manipulates JavaScript objects.
Example for Object:
let myObjectInstance: Object;
myObjectInstance = new Object();
myObjectInstance = { key: 'value' }; // Valid, as JavaScript object literals can be assigned to Object
The lowercase object type is a general type that represents any non-primitive value. It includes arrays, functions, objects, etc., but not primitives like numbers, strings, boolean, symbols, null, or undefined.
Example for object:
let myObject: object;
myObject = { key: 'value' };
myObject = [1, 2, 3];
myObject = 'Hello';
Key Insights for Object Type in TypeScript
- Structural Definition: The object type in TypeScript is instrumental for structurally defining the shape of objects. It allows developers to specify the properties and their corresponding types that an object should possess.
- Flexibility with non-primitives: ‘object’ represents any non-primitive value, such as arrays, functions, or objects. This flexibility enables the handling of diverse data structures within the same type.
- Use of Interfaces: Interfaces complement object types in TypeScript. They allow for the definition of a contract that objects must adhere to, enhancing code readability and maintainability.
- Handling Optional Properties: Object types can incorporate optional properties denoted by the ‘?’ symbol. This accommodates scenarios where specific properties may or may not exist in an object.
Conclusion
TypeScript’s Object Type is a powerful tool for shaping and defining the structures of objects in our code. With it, we can enforce strict typing on object properties, ensuring clarity and preventing inadvertent errors. We have discussed the basic syntax of the object type, illustrated through examples that will allow us to declare the blueprint of an object with specific properties and their corresponding types. Whether used directly or through interfaces and aliases.
FAQ’s
Q1. How is the object type different from other types in TypeScript?
Answer: The object type is a catch-all for non-primitive values, including arrays, functions, and objects. It excludes primitive types like numbers, strings, booleans, null, undefined, and symbols.
Q2. Is there a difference between the Object constructor and the object type in TypeScript?
Answer: Yes, there is a difference. The Object constructor refers to the built-in JavaScript constructor for creating objects, while the object type is a TypeScript type representing any non-primitive value.
Q3. How does TypeScript handle object types with dynamic properties?
Answer: TypeScript allows dynamic properties in object types through the use of index signatures. This enables the definition of objects with properties not known at compile-time.
Q4. What is the purpose of interfaces when working with object types?
Answer: Interfaces provide a way to define a contract that objects must adhere to. They enhance code readability and maintainability by explicitly declaring the expected structure of an object.
Recommended Articles
We hope that this EDUCBA information on “TypeScript Object Type” was beneficial to you. You can view EDUCBA’s recommended articles for more information.