Affirmative, it is indeed possible to achieve this task. Your issue likely arises from utilizing a "fresh" object literal (i.e., one that has not been previously assigned to any variable) and assigning it to a specific type variable in TypeScript. In such cases, TypeScript employs excess property checks to warn you if unexpected properties are added. While types in TypeScript are typically open/extendable/generalizable, they assume a closed/exact nature in instances like this because committing such actions is often erroneous.
const excessPropertyErrors: BaseClass[] = [
{ id: "a", entityId: "b", entityName: "c', commentId: "d", authorName: "e' },
{ id: "f", entityId: "g", entityName: "h", authorName: "i' },
{ id: "j", entityId: "k", entityName: "l", operationType: "m' }
]; // error! encountering issues with excess property checks here
To address this concern, several strategies can be employed.
One approach involves explicitly listing the subclasses expected. The types BaseClass
and
BaseClass | ChildClass1 | ChildClass2 | ChildClass3
share structural similarities but vary in their treatment towards "extra" properties:
const explicitlyMentionSubclasses:
Array<BaseClass | ChildClass1 | ChildClass2 | ChildClass3> = [
{ id: "a", entityId: "b", entityName: "c", commentId: "d", authorName: "e" },
{ id: "f", entityId: "g", entityName: "h", authorName: "i" },
{ id: "j", entityId: "k", entityName: "l", operationType: "m" }
]; // acceptable
This method would still trigger an excess property error if operationType
is misspelled, warranting additional caution. Nevertheless, embedding subclass information within the variable type may impose certain limitations.
Another viable option entails assigning the fresh object literal to variables annotated with the desired subclass type, subsequently populating your array with these variables:
const childClass1: ChildClass1 =
{ id: "a", entityId: "b", entityName: "c", commentId: "d", authorName: "e" };
const childClass2: ChildClass2 =
{ id: "f", entityId: "g", entityName: "h", authorName: "i" };
const childClass3: ChildClass3 =
{ id: "j", entityId: "k", entityName: "l", operationType: "m" };
const individualElements: BaseClass[] = [childClass1, childClass2, childClass3]; // appropriate
This represents one of the safest methodologies available, ensuring that each variable childClass1
, childClass2
, and childClass3
undergo relevant subclass constraints and excess property scrutiny.
... (continues)