Last active
August 1, 2020 21:22
-
-
Save nicooga/3fef73700be6ec80d777f6dc21223838 to your computer and use it in GitHub Desktop.
Hard excercise from book "Programming Typescript", solved with a hack (type assertion). The objective is to prevent users from calling `.send` on a request that is missing `method` or `url` properties..
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Data = { | |
[key: string]: string | number | Data | |
} | |
type Method = 'GET' | 'POST' | 'PUT' | 'DELETE'; | |
class Request { | |
constructor( | |
public url?: string, | |
public data?: Data, | |
public method?: Method, | |
) {} | |
setMethod(method: Method): this & { method: Method } { | |
this.method = method; | |
// HACK ALERT, HACK ALERT | |
return (<this & { method: Method}>this); | |
} | |
setUrl(url: string): this & { url: string } { | |
this.url = url; | |
// HACK ALERT, HACK ALERT | |
return (<this & { url: string}>this); | |
} | |
setData(data: Data): this { | |
this.data = data; | |
return this; | |
} | |
send(this: this & { method: Method, url: string }): this { | |
const { method, url, data } = this; | |
console.log('Sending request', { | |
method: method!, | |
url: url!, | |
data: data! | |
}); | |
return this; | |
} | |
} | |
// Funca, si no seteas el method y la url, TS va a chillar | |
new Request() | |
.setMethod('GET') | |
.setUrl('https://example.com') | |
.setData({ asdf: 2 }) | |
.send() | |
export default Request |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment