【DRAFT】ES2025 的语法糖科普
不知不觉 ES2025 都快推出了,这里分享一些比较有趣的用法。
Time API
更新的时间API
// Simplified date creation
const now = Temporal.now();
const birthday = @2024-01-15; // New date literal syntax
const meeting = @2024-12-25T10:30:00[Asia/Shanghai];
// Syntactic sugar for date/time arithmetic
const nextWeek = now + 7.days;
const lastMonth = now - 1.month;
const deadline = meeting + 2.hours + 30.minutes;
// Time range syntax
const workingHours = @09:00..17:00;
const workingDays = @Monday..Friday;
console.log(workingHours.contains(@14:30)); // true
console.log(workingDays.contains(Temporal.now().dayOfWeek)); // Check if today is a working day
Record & Tuple
对不可修改数据的支持
// Record: immutable object
const userRecord = #{
id: 1,
name: "Zhang San",
email: "zhangsan@example.com"
};
// Tuple: immutable array
const coordinates = #[10, 20, 30];
// Strict equality check
const user1 = #{ id: 1, name: "Zhang San" };
const user2 = #{ id: 1, name: "Zhang San" };
console.log(user1 === user2); // true!
// Nested structures
const complexData = #{
users: #[
#{ id: 1, name: "Zhang San" },
#{ id: 2, name: "Li Si" }
],
config: #{
theme: "dark",
language: "zh-CN"
}
};
Decimal Data Type
解决十进制精度问题来了
// Old approach: precision loss
console.log(0.1 + 0.2); // 0.30000000000000004
// New approach: precise calculation
console.log(0.1m + 0.2m); // 0.3m
// A blessing for financial calculations
const price = 19.99m;
const tax = 0.08m;
const total = price * (1m + tax);
console.log(total); // 21.5892m, perfectly accurate!
// Conversion with Number
const decimalValue = 123.456m;
const numberValue = Number(decimalValue); // 123.456
const backToDecimal = Decimal(numberValue); // 123.456m
Upgraded Import Assertions
增强了导入断言,使模块导入更安全、更灵活
// Importing JSON modules
import config from './config.json' with { type: 'json' };
// Importing CSS modules
import styles from './styles.css' with { type: 'css' };
// Importing WebAssembly modules
import wasmModule from './math.wasm' with { type: 'webassembly' };
// Dynamic import with assertions
const loadConfig = async (env) => {
const config = await import(`./config-${env}.json`, { with: { type: 'json' } });
return config.default;
};
// Conditional import
if (process.env.NODE_ENV === 'development') { import devConfig from './config-dev.json' with { type: 'json' }; }
Template String Enhancements
更强大的字符串模板
// Automatic multi-line indentation handling
const html = html`
<div class="container">
<h1>${title}</h1>
<p>${content}</p>
</div>
`; // Indentation handled automatically
// Custom interpolation handling
const sql = sql`
SELECT * FROM users
WHERE age > ${minAge}
AND city = ${city}
`; // Automatically protects against SQL injection
// Internationalized template
const message = i18n`Hello ${name}, you have ${count} new messages`; // Automatically handles locale and pluralization rules
// Styled string
const styledText = css`
color: ${primaryColor};
font-size: ${fontSize}px;
margin: ${margin};
`;
参考