Reputation: 628
i'm picking up front end development using react.In iOS, we have something call abstract class, which is implement of PROTOCOL, when doing dependency injection, i dont have to import the whole object, i just need to import the protocol to use it. Is there similar function in javascript/react to do that?
Upvotes: 0
Views: 2934
Reputation: 22423
TypeScript gives you access to interfaces and makes JS a strongly typed language. It's then transpiled to JS but during your build process.
You can declare an interface like this
interface MyComponentProps extends React.ReactProps {
id: string;
name?: string; // notice the ?, this means it can be undefined
}
and assign these props to a component like this
const MyComponent: React.FC<MyComponentProps> = (props) => {
return (
/* component here */
)
}
Check out the full docs here
Upvotes: 2
Reputation: 10538
JavaScript has no runtime type system - so there are no interfaces - and there's no concept of an abstract class either.
If you want to achieve dependency injection in React, you can utilise the React context to pass dependencies via context and hooks or higher order components, but be aware that this can obscure dependencies and make things a bit harder to test.
In general, in JavaScript, we use the module system for our 'dependency injection' and mock modules at runtime (in Jest or Webpack).
In React in particular it is pretty rare that we would pass service objects like you would see in other languages to props - Usually, I would expect javascript primitives (primitive values, arrays, objects and functions) to be passed via props, not class instances.
Upvotes: 2