Imagine we are developing a DB model for the entity Post
. Since the database stores data as strings, we need to create a parse
function that can take a raw database object and convert it into the correct Post
interface.
To replicate this, enable the noImplicitReturns: true
setting.
interface Post {
id: number
text: string
}
function parse<K extends keyof Post>(k: K, v: any): Post[K] {
switch(k) {
case 'id': return parseInt(v)
case 'text': return v.toString()
}
}
This code has two errors. First, it will not compile because TypeScript requires a default
statement in the switch
block. Secondly, it may not detect when you are checking against the wrong value. The incorrect code below would compile without errors:
function parse<K extends keyof Post>(k: K, v: any): Post[K] {
switch(k) {
case 'id': return parseInt(v)
case 'text': return v.toString()
case 'some': return v.toString() // <= error, no `some` key
default: return '' // <= this line is not needed
}
}
There is even a third error where TypeScript allows returning an incorrect value for the key. Consider the following faulty code:
function parse<K extends keyof Post>(k: K, v: any): Post[K] {
switch(k) {
case 'id': return parseInt(v)
case 'text': return 2 // <= error, it should be string, not number
default: return ''
}
}
Are these limitations of TypeScript or have I made a mistake in my implementation?