Boolean Index Signature in TypeScript
miroslavpetrik.medium.com·12w·
Discuss: Hacker News

6 min read2 days ago

Press enter or click to view image in full size

Photo by Joshua Hoehne on Unsplash

Imagine that we are building a helper function cond to pick a truthy condition:

function cond(...cases) {  for (const condition of cases) {    if (condition.hasOwnProperty(true)) {      return condition[true]    }  }}let a = 11, b = 7;const result = cond(   {[a < b]: "A is less than B"},   {[a > b]: "A is greater than B"},   {[a === b]: "A is equal to B"},);// result === "A is greater than B"

Even though this is a valid JavaScript, it won’t compile in TypeScript. Instead we get the following 3 errors:

function cond(...cases...

Similar Posts

Loading similar posts...

Keyboard Shortcuts

Navigation
Next / previous item
j/k
Open post
oorEnter
Preview post
v
Post Actions
Love post
a
Like post
l
Dislike post
d
Undo reaction
u
Recommendations
Add interest / feed
Enter
Not interested
x
Go to
Home
gh
Interests
gi
Feeds
gf
Likes
gl
History
gy
Changelog
gc
Settings
gs
Browse
gb
Search
/
General
Show this help
?
Submit feedback
!
Close modal / unfocus
Esc

Press ? anytime to show this help