Reputation: 11
As a user of some else's code I want to be able to look a function and figure out what is required based on if the type is optional.
For example:
function doSomething(required: string, optional?: string)
But as a dev who is writing code for someone else to use I want to still signify that a param is required but I want type checking as if it wasn't required since I can't guarantee my end user is also using typescript and I want to handle bad arguments gracefully.
Is it possible to have my cake and eat it too? Can I signify a param as not optional but still get compile errors if I don't check or handle the argument being undefined?
Is there a semantic difference between ?: string
and : string | undefined
Or is the solution to just have preconditions on all required fields?
Upvotes: 1
Views: 100
Reputation: 1194
If it is a matter to remember to handle undefined cases even though the value required then you can recast the passed paramters and the typescript will yell at you at compile time for not checking if this recasted value is undefined
here is an example where I used as string | undefined
inside function, for user of the function they will see that all parameters are required, but you still will be defensive.
function doSomthingElse(requiredString1: string, requiredString2: string) {}
function doSomething(required: string, required2: string) {
const recasted = required2 as string | undefined
doSomthingElse(required, recasted) //TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string
}
Upvotes: 0
Reputation: 250156
An optional parameter can be omitted in the call. A required parameter typed as T | undefined
must still be present, although you can pass in undefined
function doSomething(required: string, optional: string | undefined) {
}
doSomething("") // error in TS
doSomething("", undefined)
If the user does not use Typescript none of this really matters, as the user can pass in fewer parameters anyway.
function doSomething(required: string, optional: string) {
}
doSomething("") /// Bad in ts, but fine in JS
Upvotes: 2