Today, May 23, 2025, the Microsoft TypeScript team released "TypeScript Native Previews," a preview version of their TypeScript compiler implemented in Go. This new compiler, named "tsgo," aims to replace the current tsc
command in a future TypeScript 7 release. According to the official announcement, tsgo
can achieve up to a 10x improvement in type checking and compilation speed.
This article will guide you through the installation process for tsgo
and verify whether the performance improvements are truly realized.
TypeScript 7 Compiler Moves to Go
The current TypeScript compiler is written in TypeScript. While TypeScript is widely used in development, the increasing scale of projects has led to challenges with long build and type checking times. To address this, the TypeScript team is porting the compiler to Go, a native code language. The new compiler is planned for release as TypeScript 7.
The goal is not simply to leverage Go as a natively compiled language, but to maximize the use of shared-memory parallelism and concurrency, aiming to accelerate build times by 10x in many projects. This is expected to significantly reduce compilation and type checking wait times, thereby enhancing developer productivity.
According to Microsoft's Dev Blogs article "A 10x Faster TypeScript", indeed, speed improvements of around 10x have been reported across various codebases.
Codebase | Size (Lines) | Current (tsc) | Native (tsgo) | Speedup |
---|---|---|---|---|
VS Code | 1,505,000 | 77.8s | 7.5s | 10.4x |
Playwright | 356,000 | 11.1s | 1.1s | 10.1x |
TypeORM | 270,000 | 17.5s | 1.3s | 13.5x |
date-fns | 104,000 | 6.5s | 0.7s | 9.5x |
tRPC (server + client) | 18,000 | 5.5s | 0.6s | 9.1x |
rxjs (observable) | 2,100 | 1.1s | 0.1s | 11.0x |
(Source: A 10x Faster TypeScript - TypeScript Blog)
Initially, I was skeptical about whether the 10x speedup was truly achievable. However, now that tsgo
is available for testing, I'm eager to verify it firsthand.
Trying Out tsgo
Here's how to try out tsgo
. First, install the newly released @typescript/native-preview
package.
npm install -D @typescript/native-preview
This package provides an executable named tsgo
. Let's check its version:
npx tsgo -v
// Example output: Version 7.0.0-dev.20250523.1 (version may vary depending on installation time)
To try compiling with tsgo
, also install the typescript
package:
npm install -D typescript
Next, create a tsconfig.json
file. Since tsgo
is still in preview and doesn't yet offer project initialization features like --init
, we'll generate it using the existing tsc
command.
npx tsc --init
This will create tsconfig.json
. For this verification, we'll use the following settings:
{
"compilerOptions": {
"target": "esnext",
"lib": ["esnext", "dom", "dom.iterable"],
"module": "NodeNext",
"strict": true,
"skipLibCheck": true
}
}
Compilation Speed Comparison: tsc
vs tsgo
Let's compare the compilation speeds of tsc
and tsgo
using a moderately sized TypeScript codebase.
The following is a hypothetical e-commerce backend processing TypeScript code (approx. 700 lines) that incorporates various TypeScript features (interfaces, classes, type aliases, generics, enums, type guards, etc.).
Verification TypeScript Code (approx. 700 lines)
// --- Constants and Enums ---
/**
* An enum defining product categories.
*/
enum ProductCategory {
Electronics = "Electronics",
Books = "Books",
HomeAppliances = "Home Appliances",
Clothing = "Clothing",
Food = "Food",
Sports = "Sports"
}
/**
* An enum defining order statuses.
*/
enum OrderStatus {
Pending = "Pending",
Processing = "Processing",
Shipped = "Shipped",
Delivered = "Delivered",
Cancelled = "Cancelled"
}
/**
* An enum defining user roles.
*/
enum UserRole {
Customer = "Customer",
Admin = "Admin",
Seller = "Seller"
}
/**
* An enum defining payment methods.
*/
enum PaymentMethod {
CreditCard = "Credit Card",
PayPal = "PayPal",
BankTransfer = "Bank Transfer",
CashOnDelivery = "Cash on Delivery"
}
// --- Interfaces ---
/**
* Base entity interface (with ID, creation, and update timestamps).
*/
interface BaseEntity {
id: string;
createdAt: Date;
updatedAt: Date;
}
/**
* Interface defining product attributes.
*/
interface Product extends BaseEntity {
name: string;
description: string;
price: number;
category: ProductCategory;
stock: number;
imageUrl: string;
sellerId: string;
rating?: number; // Optional
reviewsCount?: number; // Optional
}
/**
* Interface defining user information.
*/
interface User extends BaseEntity {
username: string;
email: string;
passwordHash: string;
role: UserRole;
address?: Address; // Optional
phone?: string; // Optional
}
/**
* Interface defining an address.
*/
interface Address {
street: string;
city: string;
state: string;
zipCode: string;
country: string;
}
/**
* Interface defining an order item.
*/
interface OrderItem {
productId: string;
productName: string;
quantity: number;
priceAtOrder: number;
}
/**
* Interface defining an order.
*/
interface Order extends BaseEntity {
userId: string;
items: OrderItem[];
totalAmount: number;
status: OrderStatus;
shippingAddress: Address;
paymentMethod: PaymentMethod;
paymentStatus: 'Paid' | 'Unpaid';
shippedDate?: Date;
deliveredDate?: Date;
}
/**
* Interface defining a review.
*/
interface Review extends BaseEntity {
productId: string;
userId: string;
rating: number; // 1-5
comment: string;
}
/**
* Interface defining a payment transaction.
*/
interface PaymentTransaction extends BaseEntity {
orderId: string;
userId: string;
amount: number;
method: PaymentMethod;
transactionId: string;
status: 'Success' | 'Failed' | 'Refunded';
}
// --- Type Aliases and Utility Types ---
/**
* Type alias for user credentials.
*/
type UserCredentials = Pick<User, 'username' | 'passwordHash'>;
/**
* Type for new entities (without ID or timestamps).
*/
type New<T extends BaseEntity> = Omit<T, 'id' | 'createdAt' | 'updatedAt'>;
/**
* Common structure for API responses.
*/
type ApiResponse<T> = {
success: boolean;
data?: T;
message?: string;
error?: string;
};
// --- Classes (Data Models and Services) ---
/**
* Mock for a simple data store.
*/
class InMemoryDatabase<T extends BaseEntity> {
private collection: Map<string, T>;
constructor() {
this.collection = new Map<string, T>();
}
add(item: New<T>): T {
const id = `entity_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
const now = new Date();
const newItem: T = { ...item, id, createdAt: now, updatedAt: now } as T;
this.collection.set(id, newItem);
console.log(`[LOG] Added item to collection: ${id}`); // Add log instead of decorator
return newItem;
}
get(id: string): T | undefined {
const result = this.collection.get(id);
console.log(`[LOG] Get item by ID '${id}': ${result ? 'found' : 'not found'}`); // Add log instead of decorator
return result;
}
getAll(): T[] {
const result = Array.from(this.collection.values());
console.log(`[LOG] Get all items. Count: ${result.length}`); // Add log instead of decorator
return result;
}
update(id: string, updates: Partial<Omit<T, 'id' | 'createdAt'>>): T | undefined {
const existing = this.collection.get(id);
if (!existing) {
console.log(`[LOG] Update item ID '${id}': not found`); // Add log instead of decorator
return undefined;
}
const updatedItem = { ...existing, ...updates, updatedAt: new Date() };
this.collection.set(id, updatedItem);
console.log(`[LOG] Update item ID '${id}': success`); // Add log instead of decorator
return updatedItem;
}
delete(id: string): boolean {
const result = this.collection.delete(id);
console.log(`[LOG] Delete item ID '${id}': ${result ? 'success' : 'failed'}`); // Add log instead of decorator
return result;
}
findBy<K extends keyof T>(key: K, value: T[K]): T[] {
const result = Array.from(this.collection.values()).filter(item => item[key] === value);
console.log(`[LOG] Find items by key '${String(key)}' with value '${value}'. Found: ${result.length}`); // Add log instead of decorator
return result;
}
}
// Data store instances for each entity
const usersDb = new InMemoryDatabase<User>();
const productsDb = new InMemoryDatabase<Product>();
const ordersDb = new InMemoryDatabase<Order>();
const reviewsDb = new InMemoryDatabase<Review>();
const paymentsDb = new InMemoryDatabase<PaymentTransaction>();
/**
* Service handling user-related logic.
*/
class UserService {
private db: InMemoryDatabase<User>;
constructor(db: InMemoryDatabase<User>) {
this.db = db;
}
async registerUser(userData: New<User>): Promise<ApiResponse<User>> {
console.log(`[LOG] Method 'registerUser' called.`); // Add log instead of decorator
const existingUser = this.db.findBy('username', userData.username);
if (existingUser.length > 0) {
return { success: false, error: 'Username already exists.' };
}
// Password hashing (needs more complex actual implementation)
userData.passwordHash = `hashed_${userData.passwordHash}_${Date.now()}`;
const newUser = this.db.add(userData);
return { success: true, data: newUser };
}
async authenticateUser(credentials: UserCredentials): Promise<ApiResponse<User>> {
console.log(`[LOG] Method 'authenticateUser' called.`); // Add log instead of decorator
const users = this.db.findBy('username', credentials.username);
const user = users[0];
if (!user) {
return { success: false, error: 'User not found.' };
}
// Password comparison (actual hash comparison)
if (user.passwordHash === `hashed_${credentials.passwordHash}_${user.createdAt.getTime()}`) { // Simple comparison
return { success: true, data: user };
}
return { success: false, error: 'Invalid credentials.' };
}
getUserProfile(userId: string): ApiResponse<User> {
console.log(`[LOG] Method 'getUserProfile' called.`); // Add log instead of decorator
const user = this.db.get(userId);
if (!user) {
return { success: false, error: 'User not found.' };
}
// Return without password hash
const { passwordHash, ...safeUser } = user;
return { success: true, data: safeUser as User };
}
updateUserProfile(userId: string, updates: Partial<Omit<User, 'id' | 'createdAt' | 'passwordHash'>>): ApiResponse<User> {
console.log(`[LOG] Method 'updateUserProfile' called.`); // Add log instead of decorator
const updatedUser = this.db.update(userId, updates);
if (!updatedUser) {
return { success: false, error: 'User not found.' };
}
const { passwordHash, ...safeUser } = updatedUser;
return { success: true, data: safeUser as User };
}
}
/**
* Service handling product-related logic.
*/
class ProductService {
private db: InMemoryDatabase<Product>;
constructor(db: InMemoryDatabase<Product>) {
this.db = db;
}
async addProduct(productData: New<Product>): Promise<ApiResponse<Product>> {
console.log(`[LOG] Method 'addProduct' called.`); // Add log instead of decorator
if (productData.price <= 0 || productData.stock < 0) {
return { success: false, error: 'Price and stock must be positive.' };
}
const newProduct = this.db.add(productData);
return { success: true, data: newProduct };
}
getProduct(productId: string): ApiResponse<Product> {
console.log(`[LOG] Method 'getProduct' called.`); // Add log instead of decorator
const product = this.db.get(productId);
if (!product) {
return { success: false, error: 'Product not found.' };
}
return { success: true, data: product };
}
getAllProducts(category?: ProductCategory): ApiResponse<Product[]> {
console.log(`[LOG] Method 'getAllProducts' called.`); // Add log instead of decorator
let products = this.db.getAll();
if (category) {
products = products.filter(p => p.category === category);
}
return { success: true, data: products };
}
updateProduct(productId: string, updates: Partial<Omit<Product, 'id' | 'createdAt'>>): ApiResponse<Product> {
console.log(`[LOG] Method 'updateProduct' called.`); // Add log instead of decorator
const updatedProduct = this.db.update(productId, updates);
if (!updatedProduct) {
return { success: false, error: 'Product not found.' };
}
return { success: true, data: updatedProduct };
}
deleteProduct(productId: string, adminId: string): ApiResponse<boolean> { // Admin only
console.log(`[LOG] Method 'deleteProduct' called.`); // Add log instead of decorator
const product = this.db.get(productId);
if (!product) {
return { success: false, error: 'Product not found.' };
}
// Usually, role check for adminId is required
if (this.db.delete(productId)) {
return { success: true, data: true, message: 'Product deleted successfully.' };
}
return { success: false, error: 'Failed to delete product.' };
}
}
/**
* Service handling order-related logic.
*/
class OrderService {
private ordersDb: InMemoryDatabase<Order>;
private productsDb: InMemoryDatabase<Product>;
private usersDb: InMemoryDatabase<User>;
constructor(ordersDb: InMemoryDatabase<Order>, productsDb: InMemoryDatabase<Product>, usersDb: InMemoryDatabase<User>) {
this.ordersDb = ordersDb;
this.productsDb = productsDb;
this.usersDb = usersDb;
}
async createOrder(userId: string, items: Array<{ productId: string; quantity: number }>, shippingAddress: Address, paymentMethod: PaymentMethod): Promise<ApiResponse<Order>> {
console.log(`[LOG] Method 'createOrder' called.`); // Add log instead of decorator
const user = this.usersDb.get(userId);
if (!user) {
return { success: false, error: 'User not found.' };
}
const orderItems: OrderItem[] = [];
let totalAmount = 0;
for (const item of items) {
const product = this.productsDb.get(item.productId);
if (!product) {
return { success: false, error: `Product with ID ${item.productId} not found.` };
}
if (product.stock < item.quantity) {
return { success: false, error: `Not enough stock for product '${product.name}'. Available: ${product.stock}, Requested: ${item.quantity}.` };
}
orderItems.push({
productId: product.id,
productName: product.name,
quantity: item.quantity,
priceAtOrder: product.price
});
totalAmount += product.price * item.quantity;
// Decrease stock
this.productsDb.update(product.id, { stock: product.stock - item.quantity });
}
const newOrder: New<Order> = {
userId,
items: orderItems,
totalAmount,
status: OrderStatus.Pending,
shippingAddress,
paymentMethod,
paymentStatus: 'Unpaid'
};
const createdOrder = this.ordersDb.add(newOrder);
return { success: true, data: createdOrder };
}
getOrder(orderId: string): ApiResponse<Order> {
console.log(`[LOG] Method 'getOrder' called.`); // Add log instead of decorator
const order = this.ordersDb.get(orderId);
if (!order) {
return { success: false, error: 'Order not found.' };
}
return { success: true, data: order };
}
getUserOrders(userId: string): ApiResponse<Order[]> {
console.log(`[LOG] Method 'getUserOrders' called.`); // Add log instead of decorator
const orders = this.ordersDb.findBy('userId', userId);
return { success: true, data: orders };
}
updateOrderStatus(orderId: string, newStatus: OrderStatus): ApiResponse<Order> {
console.log(`[LOG] Method 'updateOrderStatus' called.`); // Add log instead of decorator
const updatedOrder = this.ordersDb.update(orderId, { status: newStatus });
if (!updatedOrder) {
return { success: false, error: 'Order not found.' };
}
// Additional processing based on status (e.g., setting shipped date)
if (newStatus === OrderStatus.Shipped && !updatedOrder.shippedDate) {
this.ordersDb.update(orderId, { shippedDate: new Date() });
} else if (newStatus === OrderStatus.Delivered && !updatedOrder.deliveredDate) {
this.ordersDb.update(orderId, { deliveredDate: new Date() });
} else if (newStatus === OrderStatus.Cancelled) {
// Stock return process on cancellation
for (const item of updatedOrder.items) {
const product = this.productsDb.get(item.productId);
if (product) {
this.productsDb.update(product.id, { stock: product.stock + item.quantity });
}
}
}
return { success: true, data: this.ordersDb.get(orderId)! }; // Return the latest updated order
}
}
/**
* Service handling payment-related logic.
*/
class PaymentService {
private paymentsDb: InMemoryDatabase<PaymentTransaction>;
private ordersDb: InMemoryDatabase<Order>;
constructor(paymentsDb: InMemoryDatabase<PaymentTransaction>, ordersDb: InMemoryDatabase<Order>) {
this.paymentsDb = paymentsDb;
this.ordersDb = ordersDb;
}
async processPayment(orderId: string, userId: string, amount: number, method: PaymentMethod): Promise<ApiResponse<PaymentTransaction>> {
console.log(`[LOG] Method 'processPayment' called.`); // Add log instead of decorator
const order = this.ordersDb.get(orderId);
if (!order || order.userId !== userId || order.totalAmount !== amount || order.paymentStatus === 'Paid') {
return { success: false, error: 'Invalid order or order already paid.' };
}
// Simulate integration with a real payment gateway here
const transactionId = `txn_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`;
const status = Math.random() > 0.1 ? 'Success' : 'Failed'; // 90% chance of success
const newPayment: New<PaymentTransaction> = {
orderId,
userId,
amount,
method,
transactionId,
status
};
const createdPayment = this.paymentsDb.add(newPayment);
if (status === 'Success') {
// Update order payment status
this.ordersDb.update(orderId, { paymentStatus: 'Paid', status: OrderStatus.Processing });
return { success: true, data: createdPayment, message: 'Payment successful!' };
} else {
return { success: false, error: 'Payment failed.', data: createdPayment };
}
}
getPaymentHistory(userId: string): ApiResponse<PaymentTransaction[]> {
console.log(`[LOG] Method 'getPaymentHistory' called.`); // Add log instead of decorator
const payments = this.paymentsDb.findBy('userId', userId);
return { success: true, data: payments };
}
}
/**
* Service handling review-related logic.
*/
class ReviewService {
private reviewsDb: InMemoryDatabase<Review>;
private productsDb: InMemoryDatabase<Product>;
constructor(reviewsDb: InMemoryDatabase<Review>, productsDb: InMemoryDatabase<Product>) {
this.reviewsDb = reviewsDb;
this.productsDb = productsDb;
}
async submitReview(reviewData: New<Review>): Promise<ApiResponse<Review>> {
console.log(`[LOG] Method 'submitReview' called.`); // Add log instead of decorator
if (reviewData.rating < 1 || reviewData.rating > 5) {
return { success: false, error: 'Rating must be between 1 and 5.' };
}
const product = this.productsDb.get(reviewData.productId);
if (!product) {
return { success: false, error: 'Product not found for review.' };
}
const newReview = this.reviewsDb.add(reviewData);
// Update product's average rating and review count (simple calculation)
const productReviews = this.reviewsDb.findBy('productId', product.id);
const totalRating = productReviews.reduce((sum, r) => sum + r.rating, 0);
const newAverageRating = totalRating / productReviews.length;
this.productsDb.update(product.id, {
rating: parseFloat(newAverageRating.toFixed(1)),
reviewsCount: productReviews.length
});
return { success: true, data: newReview };
}
getProductReviews(productId: string): ApiResponse<Review[]> {
console.log(`[LOG] Method 'getProductReviews' called.`); // Add log instead of decorator
const reviews = this.reviewsDb.findBy('productId', productId);
return { success: true, data: reviews };
}
getUserReviews(userId: string): ApiResponse<Review[]> {
console.log(`[LOG] Method 'getUserReviews' called.`); // Add log instead of decorator
const reviews = this.reviewsDb.findBy('userId', userId);
return { success: true, data: reviews };
}
}
// --- Main Application / Simulation ---
// Create service instances
const userService = new UserService(usersDb);
const productService = new ProductService(productsDb);
const orderService = new OrderService(ordersDb, productsDb, usersDb);
const paymentService = new PaymentService(paymentsDb, ordersDb);
const reviewService = new ReviewService(reviewsDb, productsDb);
async function simulateECWorkflow() {
console.log("--- Starting EC Site Backend Processing Simulation ---");
// 1. User Registration and Login
console.log("\n--- User Registration and Login ---");
const userResult = await userService.registerUser({
username: "testuser",
email: "[email protected]",
passwordHash: "password123",
role: UserRole.Customer,
address: { street: "123 Main St", city: "Anytown", state: "CA", zipCode: "90210", country: "USA" }
});
let currentUser: User | undefined;
if (userResult.success && userResult.data) {
console.log("User registration successful:", userResult.data.username);
currentUser = userResult.data;
const loginResult = await userService.authenticateUser({ username: "testuser", passwordHash: "password123" });
if (loginResult.success && loginResult.data) {
console.log("Login successful:", loginResult.data.username);
} else {
console.error("Login failed:", loginResult.error);
}
} else {
console.error("User registration failed:", userResult.error);
return;
}
// 2. Add Products (assuming Seller or Admin role)
console.log("\n--- Adding Products ---");
const product1Result = await productService.addProduct({
name: "Wireless Headphones",
description: "High-quality noise-cancelling headphones.",
price: 199.99,
category: ProductCategory.Electronics,
stock: 50,
imageUrl: "http://example.com/hp.jpg",
sellerId: "seller_admin_1" // Placeholder ID
});
let headphoneProduct: Product | undefined;
if (product1Result.success && product1Result.data) {
console.log("Product added successfully:", product1Result.data.name);
headphoneProduct = product1Result.data;
} else {
console.error("Failed to add product:", product1Result.error);
return;
}
const product2Result = await productService.addProduct({
name: "TypeScript Deep Dive",
description: "Comprehensive guide to TypeScript.",
price: 39.99,
category: ProductCategory.Books,
stock: 100,
imageUrl: "http://example.com/ts_book.jpg",
sellerId: "seller_admin_1"
});
let bookProduct: Product | undefined;
if (product2Result.success && product2Result.data) {
console.log("Product added successfully:", product2Result.data.name);
bookProduct = product2Result.data;
} else {
console.error("Failed to add product:", product2Result.error);
return;
}
// 3. Get All Products and Category-specific Products
console.log("\n--- Retrieving Product Lists ---");
const allProductsResult = productService.getAllProducts();
if (allProductsResult.success && allProductsResult.data) {
console.log("Total products:", allProductsResult.data.length);
}
const electronicsProductsResult = productService.getAllProducts(ProductCategory.Electronics);
if (electronicsProductsResult.success && electronicsProductsResult.data) {
console.log("Electronics products:", electronicsProductsResult.data.length);
}
// 4. Create an Order
console.log("\n--- Creating an Order ---");
if (currentUser && headphoneProduct && bookProduct) {
const orderResult = await orderService.createOrder(
currentUser.id,
[
{ productId: headphoneProduct.id, quantity: 1 },
{ productId: bookProduct.id, quantity: 2 }
],
currentUser.address!, // Address always exists as it was set during registration
PaymentMethod.CreditCard
);
let currentOrder: Order | undefined;
if (orderResult.success && orderResult.data) {
console.log("Order created successfully. Total amount:", orderResult.data.totalAmount, "Status:", orderResult.data.status);
currentOrder = orderResult.data;
const updatedHeadphoneStock = productService.getProduct(headphoneProduct.id);
console.log("New headphone stock:", updatedHeadphoneStock.success ? updatedHeadphoneStock.data?.stock : 'Failed to retrieve');
} else {
console.error("Failed to create order:", orderResult.error);
return;
}
// 5. Process Payment
console.log("\n--- Processing Payment ---");
if (currentOrder) {
const paymentResult = await paymentService.processPayment(
currentOrder.id,
currentOrder.userId,
currentOrder.totalAmount,
currentOrder.paymentMethod
);
if (paymentResult.success && paymentResult.data) {
console.log("Payment successful! Transaction ID:", paymentResult.data.transactionId);
const updatedOrder = orderService.getOrder(currentOrder.id);
console.log("Order status after payment:", updatedOrder.success ? updatedOrder.data?.status : 'Failed to retrieve');
} else {
console.error("Payment failed:", paymentResult.error);
}
}
// 6. Update Order Status (Shipped, Delivered)
console.log("\n--- Updating Order Status ---");
if (currentOrder) {
const shippedResult = await orderService.updateOrderStatus(currentOrder.id, OrderStatus.Shipped);
if (shippedResult.success) {
console.log("Order updated to Shipped:", shippedResult.data?.status);
}
const deliveredResult = await orderService.updateOrderStatus(currentOrder.id, OrderStatus.Delivered);
if (deliveredResult.success) {
console.log("Order updated to Delivered:", deliveredResult.data?.status);
}
}
// 7. Submit Product Review
console.log("\n--- Submitting Product Review ---");
if (currentUser && headphoneProduct) {
const reviewResult = await reviewService.submitReview({
productId: headphoneProduct.id,
userId: currentUser.id,
rating: 5,
comment: "Great sound quality! I love the design too."
});
if (reviewResult.success) {
console.log("Review submitted successfully. Product ID:", reviewResult.data?.productId);
const updatedProduct = productService.getProduct(headphoneProduct.id);
console.log("New headphone product rating:", updatedProduct.success ? updatedProduct.data?.rating : 'Failed to retrieve');
console.log("Headphone product review count:", updatedProduct.success ? updatedProduct.data?.reviewsCount : 'Failed to retrieve');
} else {
console.error("Failed to submit review:", reviewResult.error);
}
}
} else {
console.error("Skipped order processing due to missing required information.");
}
console.log("\n--- EC Site Backend Processing Simulation Ended ---");
}
// Run simulation
simulateECWorkflow();
// Example of Type Guard
function isProduct(obj: any): obj is Product {
return (obj as Product).category !== undefined;
}
const unknownItem: any = { name: "Test", price: 100, category: ProductCategory.Books };
if (isProduct(unknownItem)) {
console.log(`\nType Guard: This is a product. Category: ${unknownItem.category}`);
}
// Example of Generic Utility Function
function safeParseJSON<T>(jsonString: string): T | null {
try {
return JSON.parse(jsonString) as T;
} catch (e) {
console.error("JSON parsing error:", e);
return null;
}
}
const jsonProduct = '{"id": "prod_1", "name": "Generic Item", "description": "...", "price": 10.0, "category": "Electronics", "stock": 5, "imageUrl": "url", "sellerId": "seller1", "createdAt": "2023-01-01T00:00:00Z", "updatedAt": "2023-01-01T00:00:00Z"}';
const parsedProduct = safeParseJSON<Product>(jsonProduct);
if (parsedProduct) {
console.log("Generic Utility Function: Parsed product name:", parsedProduct.name);
}
Here are the measurement results when compiling the above code. The --extendedDiagnostics
option outputs detailed information about the compilation.
Result of npx tsc -p . --extendedDiagnostics
:
Files: 81
Lines of Library: 43159
Lines of Definitions: 0
Lines of TypeScript: 741
Lines of JavaScript: 0
Lines of JSON: 0
Lines of Other: 0
Identifiers: 47823
Symbols: 32013
Types: 1204
Instantiations: 1579
Memory used: 68645K
Assignability cache size: 232
Identity cache size: 9
Subtype cache size: 27
Strict subtype cache size: 1
I/O Read time: 0.02s
Parse time: 0.07s
ResolveLibrary time: 0.01s
Program time: 0.11s
Bind time: 0.04s
Check time: 0.10s
transformTime time: 0.01s
commentTime time: 0.00s
I/O Write time: 0.00s
printTime time: 0.02s
Emit time: 0.02s
Total time: 0.28s
Result of npx tsgo -p . --extendedDiagnostics
:
Files: 79
Lines: 41836
Identifiers: 46412
Symbols: 32216
Types: 1506
Instantiations: 1840
Memory used: 23733K
Memory allocs: 81192
Parse time: 0.016s
Bind time: 0.004s
Check time: 0.003s
Emit time: 0.001s
Total time: 0.026s
The sample code is also available in the following repository:
https://github.com/tonkotsuboy/tsgo-playground
Result: 10x Speedup is Real
Measurement Item | tsc (Traditional) | tsgo (Native Preview) | Improvement with tsgo |
---|---|---|---|
Total time | 0.28s | 0.026s | Approx. 10.8x faster |
Check time (Type Checking) | 0.10s | 0.003s | Approx. 33.3x faster |
Memory used | 68645K | 23733K | Approx. 2.9x more efficient |
From the comparison above, it can be seen that tsc
's Total time
is 0.28s, whereas tsgo
's Total time
is 0.026s, achieving a 10.8x speedup. Furthermore, the time taken for type checking (Check time
) is 0.10s for tsc
compared to 0.003s for tsgo
, indicating a roughly 30x speedup. Memory usage also shows significant improvement, with tsc
at 68645K and tsgo
at 23733K, achieving approximately 2.9x greater efficiency.
The 10x Speedup Claim Was True
In this article, we covered the installation procedure for tsgo
and compared its compilation speed. Although it was a small-scale example, we confirmed that the "10x speedup" claim is true. We eagerly await the release of TypeScript 7.
As a side note, TSKaigi 2025 is being held today, and discussions about tsgo
were buzzing throughout the venue. This is an eagerly anticipated update for TypeScript-loving developers.
Related Articles
https://devblogs.microsoft.com/typescript/announcing-typescript-native-previews/
https://devblogs.microsoft.com/typescript/typescript-native-port/
Top comments (0)