This Crazy Syntax Lets You Get An Array Element's Type
Learn how to extract the type of an array element in TypeScript using the powerful Array[number]
trick.
Need to manually type a JSON file?
I learned today that you can add a .d.json.ts
file to manually assign a type to a JSON import.
For example, if you have a data.json
file, you can create a data.d.json.ts
file and define the type inside:
// data.d.json.ts
declare const data: Record<string, string>;
export default data;
You can change the Record<string, string>
type to match the desired shape.
To make TypeScript recognize .d.json.ts
files, you need to add a setting in your tsconfig.json
:
{
"compilerOptions": {
"allowArbitraryExtensions": true
}
}
This setting lets TypeScript use .d.json.ts
files.
This technique can be particularly useful when working with large .json
files used for test fixtures. If TypeScript infers the type of all the data in the file, it can significantly slow down the TypeScript transpilation process - and your IDE.
By assigning a broader type like Record<string, string>
, TypeScript will use the specified type instead. This optimization can greatly improve the performance of your TypeScript transpilation.
Override the Type of a JSON File
Learn how to extract the type of an array element in TypeScript using the powerful Array[number]
trick.
Learn how to publish a package to npm with a complete setup including, TypeScript, Prettier, Vitest, GitHub Actions, and versioning with Changesets.
Enums in TypeScript can be confusing, with differences between numeric and string enums causing unexpected behaviors.
Is TypeScript just a linter? No, but yes.
It's a massive ship day. We're launching a free TypeScript book, new course, giveaway, price cut, and sale.
Learn why the order you specify object properties in TypeScript matters and how it can affect type inference in your functions.