In the process of developing a factory function, I am incorporating a type argument to specify the type of object being created, along with a parameter argument containing parameters that describe the object. The parameters are dependent on the specific type of object being created. An example of this is shown below:
enum EntityType {
TABLE,
BUCKET
}
type TableParams = { tableName: string }
type BucketParams = { bucketName: string }
function createEntity (type: EntityType.TABLE, params: TableParams): void
function createEntity (type: EntityType.BUCKET, params: BucketParams): void
function createEntity (type: EntityType, params: TableParams | BucketParams): void {
switch(type) {
case EntityType.TABLE:
console.log('table name:', params.tableName)
break
case EntityType.BUCKET:
console.log('bucket name:', params.bucketName)
break
}
}
The use of function overloads ensures that users can only invoke the function with the appropriate parameters based on the entity type, for example:
createEntity(EntityType.TABLE, { tableName: 'foo' })
createEntity(EntityType.BUCKET, { bucketName: 'bar' })
createEntity(EntityType.BUCKET, { tableName: 'fox' }) // => No overload matches this call.
The first two calls execute successfully, however, the third call results in a compilation error stating "No overload matches this call."
Yet how can I enforce type safety within the function? In other words, the provided sample does not compile because of the message "Property 'tableName' does not exist on type 'TableParams | BucketParams'."
Isn't TypeScript supposed to infer the type of the params
argument based on which of the two function overloads is matched?