Hardhat provides native support for TypeScript. Here are the main advantages and methods of using TypeScript:
1. Project Initialization
Create a project with TypeScript template:
bashnpx hardhat init # Select "Create a TypeScript project"
2. Type-Safe Contract Interaction
Hardhat automatically generates type definitions:
typescriptimport { ethers } from "hardhat"; async function main() { const Contract = await ethers.getContractFactory("MyContract"); const contract = await Contract.deploy() as MyContract; // Type-safe function calls await contract.setValue(42); const value = await contract.value(); console.log("Value:", value.toNumber()); }
3. Using TypeChain
TypeChain generates type definitions for contract ABIs:
bashnpm install --save-dev typechain @typechain/ethers-v5
Configure in hardhat.config.ts:
typescriptimport "@typechain/hardhat";
Generated type definitions:
typescriptimport { MyContract } from "../typechain-types"; const contract: MyContract = await contractFactory.deploy();
4. Type Safety in Tests
typescriptimport { expect } from "chai"; import { ethers } from "hardhat"; import { MyContract } from "../typechain-types"; describe("MyContract", function () { let contract: MyContract; beforeEach(async function () { const ContractFactory = await ethers.getContractFactory("MyContract"); contract = await ContractFactory.deploy(); await contract.deployed(); }); it("should set value correctly", async function () { await contract.setValue(100); expect(await contract.value()).to.equal(100); }); });
5. Type-Safe Configuration Files
Use TypeScript configuration file hardhat.config.ts:
typescriptimport { HardhatUserConfig } from "hardhat/config"; import "@nomicfoundation/hardhat-toolbox"; const config: HardhatUserConfig = { solidity: "0.8.19", networks: { sepolia: { url: process.env.SEPOLIA_RPC_URL || "", accounts: process.env.PRIVATE_KEY ? [process.env.PRIVATE_KEY] : [] } } }; export default config;
6. Environment Variable Type Definitions
typescript// .env.d.ts declare namespace NodeJS { interface ProcessEnv { SEPOLIA_RPC_URL: string; PRIVATE_KEY: string; ETHERSCAN_API_KEY: string; } }
Advantages:
- Compile-time type checking
- Intelligent code completion
- Safer refactoring
- Reduced runtime errors
- Better code documentation
- More efficient team collaboration