Hi all~!
When defining types, I can mainly think of 3 common ways for doing it:
1 - Defining the "actual" type
e.g.
interface MyType {
foo: number;
}
2 - Passing the related type alias
type MyNumericType = number;
interface MyType {
foo: MyNumericType;
}
3 - Indexed access type
type MyNumericType = number;
interface MyIndexedType {
bar: MyNumericType;
}
interface MyType {
foo: MyIndexedType['bar']; // instead of `MyNumericType` or `number`
}
So I was wondering if there were commonly known best practices to know which way is more suitable?
In my case, I am often facing below situation and never sure which way to pick.
type MyCustomType = number | string;
type ComponentCProps = {
c: MyCustomType;
}
function ComponentC({ c }: ComponentCProps) {
// ...
}
type ComponentBProps = {
b: MyCustomType;
}
function ComponentB({ b }: ComponentBProps) {
// ...
}
type ComponentAProps = {
a: boolean;
b: number | string; // OR ComponentBProps['b'] ? OR MyCustomType ?
c: number | string; // OR ComponentCProps['c'] ? OR MyCustomType ?
}
function ComponentA({ a, b, c }: ComponentAProps) {
if (!a) return null;
return (
<div>
<ComponentB b={b} />
<ComponentC c={c} />
</div>
);
}
- seems clearer than 2) and 3) but harder to maintain, 2) sounds easier to maintain but seems not really convenient to always have to dig into the type definitions and see what type/type definition I need to put in my parent component, 3) seems the easiest to use but not so clean...
Any idea perhaps?