2024-05-06 20:40:05 +00:00
|
|
|
---
|
2024-10-30 17:04:36 +00:00
|
|
|
date: 20201126
|
2024-05-06 20:40:05 +00:00
|
|
|
id: f8951d1c-bddf-49c3-bd61-fdfffc412deb
|
|
|
|
title: predicate
|
|
|
|
---
|
|
|
|
|
|
|
|
# Origin
|
|
|
|
|
|
|
|
Latin praedicatus "something declared"
|
|
|
|
|
|
|
|
# Definition
|
|
|
|
|
|
|
|
A function that returns a single boolean value
|
|
|
|
|
|
|
|
# Examples
|
|
|
|
|
|
|
|
``` typescript
|
|
|
|
type Predicate = () => boolean
|
|
|
|
|
|
|
|
function isTurkey(x: string) {
|
|
|
|
return x === 'turkey'
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
``` typescript
|
|
|
|
interface Dog {
|
|
|
|
bark: 'dog'
|
|
|
|
}
|
|
|
|
|
|
|
|
interface Cat {
|
|
|
|
meow: 'cat'
|
|
|
|
}
|
|
|
|
|
|
|
|
function isCat(animal): animal is Cat {
|
|
|
|
return (animal as Cat).meow !== undefined
|
|
|
|
}
|
|
|
|
|
|
|
|
function makeSound(animal: Cat | Dog) {
|
|
|
|
if (isCat(animal)) {
|
|
|
|
animal.meow
|
|
|
|
} else {
|
|
|
|
animal.bark
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|