代码片段与知识卡片,即用即走,可一键复制 / 保存转发
type EventName<T extends string> = `on${Capitalize<T>}`
// produces: 'onClick' | 'onChange' | 'onSubmit'
type DomEvents = EventName<'click' | 'change' | 'submit'>
// type safe CSS properties
type CSSVar<T extends string> = `--${T}`type Config = {
theme: 'light' | 'dark' | 'system'
colors: Record<string, string>
}
// with a normal annotation you lose the literal type
const config1: Config = {
theme: 'dark',// nothing stops you from having both data and error at once
type ApiResponse = {
data?: User
error?: string
loading?: boolean
}
function debounce(fn, delay) {
let timer = null;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}function throttle(fn, gap) {
let last = 0;
return function (...args) {
const t = Date.now();
if (t - last >= gap) { last = t; fn.apply(this, args); }
};
}