-1

Is there a "golden rule" when one uses types that share some properties? take the following example: Say we have 2 types that share some properties(p1,p2):

typeA {
    p1:string,
    p2:number,
    p3:boolean
}

typeB {
    p1:string,
    p2:number,
    p4:string
}

now say that there is a function that uses p1 and p2. What is the best way to type that function?

a:

function doStuff(val: string, options: typeA | typeB) {
    // do stuff with val,p1,p2
}

//use
doStuff('test',options)

b:

newLocalType {
    p1:string, 
    p2:string 
}

function doStuff(val: string, options: newLocalType) {
    // do stuff with val,p1,p2
} 

//use
doStuff('test',options)

c.

function doStuff(val: string, p1:string, p2:string) {
    // do stuff with val,p1,p2
}

//use
doStuff('test',options.p1,options.p2)

Pros and cons I can think of: the advantages with option a are that we keep the types separated in their own files but it can grow if we want to use this function for more types? the advantages with option b are that we type locally every time to specify exactly what we want but we end up maybe with a lot of types in each file. with option c we are more verbose and break down things a bit better but can it get "too verbose"? and what if the function ends up taking 20 extra arguments?

New contributor
traveler24662 is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

put on hold as too broad by gnat, Jörg W Mittag, BobDalgleish, GlenH7 2 days ago

Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Avoid asking multiple distinct questions at once. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

1

I understand your question as when to introduce a common superclass of two pre-existing classes.

I'd recommend not to base your decision on technical aspects like the existence of some common fields, but on the semantics of the classes. I'd introduce a common superclass only if it represents a concept that's semantically meaningful.

A rule of thumb might be to search for a name for the superclass. If nothing better than Has_P1_and_P2 comes to your mind, then keep the classes separate.

Not the answer you're looking for? Browse other questions tagged or ask your own question.