I cant figure out how to write the types so the dev has the suggested types for the specific prop no matter how he passes the data to the prop.
As an example. I have a component and passing array of values via the prop:
<Component someProp={[{ fancyName: 'test' }]} />
Now if I pass it like this directly to the prop, I get auto suggested types when I start typing them, but if I do something like this:
somefunction = () => {
return [{ fancyName: 'test' }]
}
<Component someProp={this.someFunction()} />
Then I dont get auto suggested types at all even tho the types apply.
And in the types I would have something like this:
export interface SomeTypes{
someProp: Array<SecondTypes>
}
export interface SecondTypes{
fancyName: string
}
In order to fix this I can do this:
somefunction = (): SomeTypes => {
return [{ fancyName: 'test' }]
}
But then all the devs has to apply the types like this for the function and not all will. I want to force them to use the types and get suggestions even if they pass the values via function return. I hope the problem is clear and someone can suggest a solution.
CodePudding user response:
It sounds like what you're looking for is nominal typing.
Probably the most OOP-friendly nominally typed approach is to use custom model classes:
import { Component } from "react"
class Named {
constructor(public fancyName: string) {}
}
class SomeComponent extends Component<{ someProp: Named[] }> {}
class TestComponent extends Component {
someFunction = () => {
return [new Named('test')]
}
render() {
return <SomeComponent someProp={this.someFunction()} />
}
}
CodePudding user response:
With React Functional component you can do like this:
import { React, FC } from 'react';
interface IMyCompProps {
somefunction: () => SomeTypes
}
const MyComp: FC<IMyCompProps> ({somefunction}) => {
return <></>
}
function myFunc() {
return [{ fancyName: 'test' }]
}
<MyComp somefunction={myFunc}/>
and it should do the trick.