What’s new in TypeScript 5.4 ?
Last Updated :
09 Apr, 2024
TypeScript 5.4 brings forth several new capabilities and refinements, aiming to enhance developer productivity and code quality. Some of the new capabilities that are added or Introduced in TypeScript 5.4 are as follows:
Variadic Tuple Types
Variadic tuple types allow developers to define tuple types with a variable number of elements, enhancing flexibility and type safety.
Syntax:
type Concat<T extends any[], U extends any[]> = [...T, ...U];
Example: Concatenating Two Tuples. In this example, we define a type Concat that concatenates two tuples of any type and length.
JavaScript
type Concat<T extends any[],
U extends any[]> = [...T, ...U];
const result: Concat<[1, 2], [3, 4]> =
[1, 2, 3, 4];
console.log(result);
Output
[1, 2, 3, 4]
Class Property Inference from Constructors
TypeScript 5.4 allows class properties to be inferred directly from constructor arguments, reducing verbosity and improving code readability.
Syntax:
class MyClass {
constructor(public prop1: Type1, public prop2: Type2) {}
}
Example: Creating an Instance of MyClass In this example, we define a class Person with constructor parameters, which automatically infer properties.
JavaScript
class Person {
constructor(
public name: string,
public age: number) { }
}
const person = new Person('Geeks for Geeks', 22);
console.log(person.name);
console.log(person.age);
Output
Geeks for Geeks
22
Local Assignment Discouragement
TypeScript 5.4 introduces stricter checks to discourage accidental local assignments within conditions or loops, enhancing code quality and preventing potential bugs.
Syntax:
let x = 0;
if (x = 10) {
// Code block
}
Example: Discouraging Local Assignments in this example, we attempt to assign a value within a condition, triggering a compiler warning.
JavaScript
let x = 0;
if (x = 10) {
// This will raise a compiler warning
console.log('Unexpected assignment');
}
Output
Unexpected assignment
Relaxed Rules Between Optional Properties and String Index Signatures
TypeScript 5.4 relaxes the rules governing the interaction between optional properties and string index signatures, providing more flexibility in type definitions.
Syntax:
interface MyObj {
[key: string]: number;
optionalProp?: string;
}
Example: Defining an Object with Optional Property in this example, we define an interface MyObj with a string index signature and an optional property.
JavaScript
interface MyObj {
[key: string]: number;
optionalProp?: string;
}
const obj: MyObj = {
optionalProp: 'gfg',
key: 22,
};
console.log(obj.optionalProp);
console.log(obj['key']);
Output
gfg
22
Share your thoughts in the comments
Please Login to comment...