I am puzzled by why my inferred types are considered as instances of my more general collection type while my explicit types are not.
My goal was to:
Have a specific part of my application work with tightly defined collections (e.g., IParents vs IBosses).
Have another part of my application work more broadly with the same objects (as IPeople).
I expected that my explicit types would not be accepted as instances of the general indexed collection type. However, it surprised me that my inferred types were accepted. I thought the inferred type would behave similarly to my explicit type.
Do inferred types also automatically have an indexer? This aspect is not mentioned when describing the type in tooltips.
interface IPerson {
name: string
}
let personA: IPerson = { name: "X" }
let personB: IPerson = { name: "Y" }
// Indexed person collection
interface IPeople {
[id: string]: IPerson
}
// Explicit person collections
interface IParents {
mother: IPerson
father: IPerson
}
interface IBosses {
manager: IPerson
director: IPerson
}
// Explicitly-typed instances
let objPeople: IPeople = {
x: personA,
y: personB
}
let objParents: IParents = {
mother: personA,
father: personB
}
let objBosses: IBosses = {
manager: personA,
director: personB
}
// Inferred-typed instances
// Inferred type is { mother: IPerson, father: IPerson } ??
let objInferredParents = {
mother: personA,
father: personB,
}
// Inferred type is { manager: IPerson, director: IPerson } ??
let objInferredBosses = {
manager: personA,
director: personB,
}
// I want to work elsewhere with the specific types but have this be able to process them all
function processPeople(col: IPeople) {
// NOP
}
processPeople(objPeople)
// The explicit types are NOT assignable to IPeople
// "Argument of type 'IParents' is not assignable to parameter of type 'IPeople'.
// Index signature is missing in type 'IParents'."
processPeople(objParents) // ERROR
processPeople(objBosses) // ERROR
// The inferred types ARE assignable to IPeople
processPeople(objInferredParents)
processPeople(objInferredBosses)