
Atklājiet kļūdu · TypeScript
Slēptās kļūdas
Katrs no šiem astoņiem fragmentiem tiek kompilēts, pāriet nejaušā pārskatā un izskatās labi. Katrs slēpj kļūdu. Katram: pastāstiet, kas salūzīs, kādos apstākļos — un kā to atklātu.
Runājiet skaļi. Mēs interesē, kā lasāt kodu, ne stundu. Nav problēmas, ja neizdodas visus atrast.
01 Pasūtījuma veikšana
interface Notifier {
send(to: string, message: string): Promise<void>
}
class OrderService {
constructor(private readonly notifier: Notifier) {}
async placeOrder(order: Order): Promise<OrderId> {
const id = await this.repo.save(order)
this.notifier.send(order.customerEmail, `Order ${id} confirmed`)
return id
}
}
02 Profila atjaunināšana
app.post('/profile', async (req, res) => {
const profile = parseProfile(req.body)
try {
await db.profiles.update(req.user.id, profile)
} catch (err) {
logger.warn('profila atjaunināšana neizdevās', err)
}
res.status(200).json({ status: 'saglabāts' })
})
03 Komentāra dzēšana
app.delete('/comments/:id', requireAuth, async (req, res) => {
const comment = await db.comments.findById(req.params.id)
if (!comment) {
return res.status(404).end()
}
await db.comments.delete(comment.id)
res.status(204).end()
})
04 Saraksta lapošana
function paginate<T>(items: T[], page: number, pageSize: number): T[] {
const start = page * pageSize
const end = start + pageSize
return items.slice(start, end)
}
// izsaucējs
const results = paginate(rows, page, 20) // lapa sākas ar 1 UI
05 Rakstu ielāde ar autoriem
async function loadArticlesWithAuthors(): Promise<ArticleView[]> {
const articles = await db.query('SELECT * FROM articles WHERE published = true')
const views: ArticleView[] = []
for (const article of articles) {
const author = await db.query('SELECT * FROM users WHERE id = $1', [article.authorId])
views.push({ ...article, author: author[0] })
}
return views
}
06 Noklusējuma konfigurācijas risinājums
interface Settings {
retryLimit?: number
displayName?: string
}
function resolveConfig(s: Settings) {
return {
retryLimit: s.retryLimit || 3,
displayName: s.displayName || 'Anonīms',
}
}
07 Atbalsta funkcijas testēšana
function applyDiscount(price: number, percent: number): number {
return price - price * (percent / 100)
}
describe('applyDiscount', () => {
it('piemēro atlaidi', () => {
const spy = vi.fn().mockReturnValue(90)
const result = spy(100, 10)
expect(result).toBeDefined()
expect(result).toBe(90)
})
})
08 Augstākie rezultāti
function topScores(scores: number[], take = 3): number[] {
return scores.sort((a, b) => b - a).slice(0, take)
}
const results = [4, 1, 9, 2]
const podium = topScores(results)
// vēlāk citur:
renderRawResults(results) // gaidāms [4, 1, 9, 2]