I'm creating a factory function, which takes a type argument to indicate the type of object to create, plus an parameter argument with parameters describing the object, which is dependent on the type of the object. A simplified example would look like this:
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 function overloads ensure that users can only call the function with the right kind of parameters, depending on the entity type, e.g.
createEntity(EntityType.TABLE, { tableName: 'foo' })
createEntity(EntityType.BUCKET, { bucketName: 'bar' })
createEntity(EntityType.BUCKET, { tableName: 'fox' }) // => No overload matches this call.
The first two calls works just fine, but the 3rd call causes a compilation error: "No overload matches this call".
But how do I ensure type-safety inside the function? I.e. the example above doesn't actually compile because "Property 'tableName' does not exist on type 'TableParams | BucketParams'."
Shouldn't TypeScript be able to deduce the type of the params argument, based on which of the 2 function overloads matches?