vscode插件i18n-automatically扫描前后ts的对比图

Created Diff never expires
11 removals
Lines
Total
Removed
Words
Total
Removed
To continue using this feature, upgrade to
Diffchecker logo
Diffchecker Pro
186 lines
38 additions
Lines
Total
Added
Words
Total
Added
To continue using this feature, upgrade to
Diffchecker logo
Diffchecker Pro
209 lines
// test.ts
import i18n from '@/i18n'; // test.ts


import { translate } from './i18n-helper';
import { translate } from './i18n-helper';
import { ApiClient } from './api-client';
import { ApiClient } from './api-client';


// Type definitions
// Type definitions
type UserRole = 'admin' | 'editor' | 'guest';
type UserRole = 'admin' | 'editor' | 'guest';


interface User {
interface User {
id: number;
id: number;
name: string;
name: string;
age: number;
age: number;
role: UserRole;
role: UserRole;
lastLogin?: Date;
lastLogin?: Date;
}
}


// Enum with Chinese keys (as requested to keep)
// Enum with Chinese keys (as requested to keep)
enum StatusCode {
enum StatusCode {
'成功' = 200,
'成功' = 200,
'未授权' = 401,
'未授权' = 401,
'禁止访问' = 403,
'禁止访问' = 403,
'未找到' = 404,
'未找到' = 404,
'服务器错误' = 500,
'服务器错误' = 500,
}
}


// Constants with Chinese keys
// Constants with Chinese keys
const ErrorMessages = {
const ErrorMessages = {
用户未找到: 'User not found',
用户未找到: 'User not found',
无效凭证: 'Invalid credentials',
无效凭证: 'Invalid credentials',
操作未授权: 'Unauthorized operation',
操作未授权: 'Unauthorized operation',
服务暂时不可用: 'Service temporarily unavailable',
服务暂时不可用: 'Service temporarily unavailable',
};
};


// Class
// Class
class UserManager {
class UserManager {
private users: User[] = [];
private users: User[] = [];


constructor(initialUsers: User[] = []) {
constructor(initialUsers: User[] = []) {
this.users = initialUsers;
this.users = initialUsers;
console.log('用户管理系统已初始化'); // StringLiteral in console.log
console.log('用户管理系统已初始化'); // StringLiteral in console.log
}
}


addUser(user: User): void {
addUser(user: User): void {
this.users.push(user);
this.users.push(user);
console.log(`新用户 ${user.name} 已添加`); // Template literal in console.log
console.log(`新用户 ${user.name} 已添加`); // Template literal in console.log
}
}


getUser(id: number): User | undefined {
getUser(id: number): User | undefined {
return this.users.find((user) => user.id === id);
return this.users.find((user) => user.id === id);
}
}


updateUser(id: number, updateInfo: Partial<User>): void {
updateUser(id: number, updateInfo: Partial<User>): void {
const index = this.users.findIndex((user) => user.id === id);
const index = this.users.findIndex((user) => user.id === id);
if (index !== -1) {
if (index !== -1) {
this.users[index] = { ...this.users[index], ...updateInfo };
this.users[index] = { ...this.users[index], ...updateInfo };
console.log(`用户 ${id} 信息已更新`); // Template literal in console.log
console.log(`用户 ${id} 信息已更新`); // Template literal in console.log
} else {
} else {
console.error(translate(ErrorMessages.用户未找到));
console.error(translate(ErrorMessages.用户未找到));
}
}
}
}


deleteUser(id: number): void {
deleteUser(id: number): void {
const index = this.users.findIndex((user) => user.id === id);
const index = this.users.findIndex((user) => user.id === id);
if (index !== -1) {
if (index !== -1) {
this.users.splice(index, 1);
this.users.splice(index, 1);
console.log(`用户 ${id} 已删除`); // Template literal in console.log
console.log(`用户 ${id} 已删除`); // Template literal in console.log
} else {
} else {
console.error(translate(ErrorMessages.用户未找到));
console.error(translate(ErrorMessages.用户未找到));
}
}
}
}


listAllUsers(): void {
listAllUsers(): void {
console.log('所有用户:'); // StringLiteral in console.log
console.log('所有用户:'); // StringLiteral in console.log
this.users.forEach((user) => {
this.users.forEach((user) => {
console.log(
console.log(
`ID: ${user.id}, 姓名: ${user.name}, 年龄: ${user.age}, 角色: ${user.role}`,
`ID: ${user.id}, 姓名: ${user.name}, 年龄: ${user.age}, 角色: ${user.role}`,
); // Template literal in console.log
); // Template literal in console.log
});
});
}
}
}
}


// Generic function
// Generic function
function createAndLog<T>(item: T, logMessage: string): T {
function createAndLog<T>(item: T, logMessage: string): T {
console.log(logMessage, item);
console.log(logMessage, item);
return item;
return item;
}
}


// Async function
// Async function
async function fetchRemoteUserData(userId: number): Promise<User> {
async function fetchRemoteUserData(userId: number): Promise<User> {
const apiClient = new ApiClient('https://api.example.com');
const apiClient = new ApiClient('https://api.example.com');
try {
try {
const response = await apiClient.get(`/users/${userId}`);
const response = await apiClient.get(`/users/${userId}`);
if (response.status === StatusCode.成功) {
if (response.status === StatusCode.成功) {
return response.data as User;
return response.data as User;
} else {
} else {
throw new Error(`获取用户数据失败: ${response.statusText}`); // Template literal in Error message
throw new Error(`获取用户数据失败: ${response.statusText}`); // Template literal in Error message
}
}
} catch (error) {
} catch (error) {
console.error('API调用错误:', error); // StringLiteral in console.error
console.error('API调用错误:', error); // StringLiteral in console.error
throw error;
throw error;
}
}
}
}


// Decorator
// Decorator
function logMethod(
function logMethod(
target: any,
target: any,
propertyKey: string,
propertyKey: string,
descriptor: PropertyDescriptor,
descriptor: PropertyDescriptor,
) {
) {
const originalMethod = descriptor.value;
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
descriptor.value = function (...args: any[]) {
console.log(`调用方法 ${propertyKey},参数:`, args); // Template literal in console.log
console.log(`调用方法 ${propertyKey},参数:`, args); // Template literal in console.log
const result = originalMethod.apply(this, args);
const result = originalMethod.apply(this, args);
console.log(`方法 ${propertyKey} 执行完成,结果:`, result); // Template literal in console.log
console.log(`方法 ${propertyKey} 执行完成,结果:`, result); // Template literal in console.log
return result;
return result;
};
};
return descriptor;
return descriptor;
}
}


// Class using decorator
// Class using decorator
class AdvancedUserManager extends UserManager {
class AdvancedUserManager extends UserManager {
@logMethod
@logMethod
performAdvancedOperation(operation: string): string {
performAdvancedOperation(operation: string): string {
return `执行高级操作: ${operation}`; // Template literal
return `${i18n.t('demoTest-test-ts-before-19299188809a0b65e-6')}${operation}`; // Template literal
}
}
}
}


// Usage example
// Usage example
const userSystem = new AdvancedUserManager([
const userSystem = new AdvancedUserManager([
{ id: 1, name: '张三', age: 30, role: 'admin' },
{
{ id: 2, name: '李四', age: 25, role: 'editor' },
id: 1,
name: i18n.t('demoTest-test-ts-before-19299188809a0b65e-7'),
age: 30,
role: 'admin',
},
{
id: 2,
name: i18n.t('demoTest-test-ts-before-19299188809a0b65e-8'),
age: 25,
role: 'editor',
},
]);
]);


userSystem.listAllUsers();
userSystem.listAllUsers();


const newUser = createAndLog<User>(
const newUser = createAndLog<User>(
{ id: 3, name: '王五', age: 28, role: 'guest' },
{
'创建新用户:', // StringLiteral
id: 3,
name: i18n.t('demoTest-test-ts-before-19299188809a0b65e-9'),
age: 28,
role: 'guest',
},
i18n.t('demoTest-test-ts-before-19299188809a0b65e-10'),
// StringLiteral
);
);


userSystem.addUser(newUser);
userSystem.addUser(newUser);


userSystem.performAdvancedOperation('数据分析'); // StringLiteral as argument
userSystem.performAdvancedOperation(
i18n.t('demoTest-test-ts-before-19299188809a0b65e-11'),
); // StringLiteral as argument


// Async operation example
// Async operation example
(async () => {
(async () => {
try {
try {
const remoteUser = await fetchRemoteUserData(4);
const remoteUser = await fetchRemoteUserData(4);
console.log('获取到远程用户数据:', remoteUser); // StringLiteral in console.log
console.log('获取到远程用户数据:', remoteUser); // StringLiteral in console.log
userSystem.addUser(remoteUser);
userSystem.addUser(remoteUser);
} catch (error) {
} catch (error) {
console.error('获取远程用户数据失败:', error); // StringLiteral in console.error
console.error('获取远程用户数据失败:', error); // StringLiteral in console.error
}
}
})();
})();


// Internationalization example
// Internationalization example
console.log(translate('欢迎使用用户管理系统')); // StringLiteral in translate function
console.log(translate('欢迎使用用户管理系统')); // StringLiteral in translate function
console.log(
console.log(
translate('当前在线用户数: {count}', { count: userSystem['users'].length }),
translate('当前在线用户数: {count}', { count: userSystem['users'].length }),
); // Template literal in translate function
); // Template literal in translate function


// Error handling with translated messages
// Error handling with translated messages
try {
try {
throw new Error(ErrorMessages.操作未授权);
throw new Error(ErrorMessages.操作未授权);
} catch (error) {
} catch (error) {
console.error(translate('发生错误: {message}', { message: error.message })); // Template literal in translate function
console.error(translate('发生错误: {message}', { message: error.message })); // Template literal in translate function
}
}


// Date and time handling
// Date and time handling
const currentDate = new Date();
const currentDate = new Date();
console.log(`当前日期和时间: ${currentDate.toLocaleString('zh-CN')}`); // Template literal with method call
console.log(`当前日期和时间: ${currentDate.toLocaleString('zh-CN')}`); // Template literal with method call


// Array operations
// Array operations
const fruitList = ['苹果', '香蕉', '橙子', '葡萄']; // Array of StringLiterals
const fruitList = [
i18n.t('demoTest-test-ts-before-19299188809a0b65e-12'),
i18n.t('demoTest-test-ts-before-19299188809a0b65e-13'),
i18n.t('demoTest-test-ts-before-19299188809a0b65e-14'),
i18n.t('demoTest-test-ts-before-19299188809a0b65e-15'),
]; // Array of StringLiterals
console.log('水果列表:', fruitList.join('、')); // StringLiteral and Chinese separator in join
console.log('水果列表:', fruitList.join('、')); // StringLiteral and Chinese separator in join


// Object destructuring
// Object destructuring
const { name, age } = userSystem.getUser(1) || {};
const { name, age } = userSystem.getUser(1) || {};
console.log(`用户信息: 姓名 - ${name}, 年龄 - ${age}`); // Template literal
console.log(`用户信息: 姓名 - ${name}, 年龄 - ${age}`); // Template literal


// String template
// String template
const welcomeMessage = `欢迎 ${name} 访问我们的系统。您的账户已经使用了 ${age} 年。`; // Template literal
const welcomeMessage = `${i18n.t('demoTest-test-ts-before-19299188809a0b65e-16')}${name}${i18n.t('demoTest-test-ts-before-19299188809a0b65e-17')}${age}${i18n.t('demoTest-test-ts-before-19299188809a0b65e-18')}`; // Template literal
console.log(welcomeMessage);
console.log(welcomeMessage);


export { UserManager, AdvancedUserManager, fetchRemoteUserData };
export { UserManager, AdvancedUserManager, fetchRemoteUserData };