how to set a type in a component in typescript

In TypeScript, we define types and interfaces to provide strong typing in our code. When working with React components, we can also set the type of our component to ensure that it conforms to a specific set of properties and methods.

To set the type of a component, we can create an interface that defines the desired set of properties and methods. For example:

index.ts
interface MyComponentProps {
  name: string;
  age: number;
  onClick: () => void;
}
85 chars
6 lines

In this example, we define an interface MyComponentProps that requires a name property of type string, an age property of type number, and an onClick property of type () => void.

We can then set the type of our component by extending React.Component and passing our interface as a generic:

index.ts
class MyComponent extends React.Component<MyComponentProps> {
  // ...
}
73 chars
4 lines

Now, our MyComponent class is guaranteed to have the name, age, and onClick properties, and any attempt to access or set properties that are not part of the interface will result in a compilation error.

index.ts
// Usage of MyComponent
<MyComponent name="John" age={30} onClick={() => console.log('Clicked!')} />
101 chars
3 lines

In the above example, we are able to set the required properties on the MyComponent instance without any errors, thanks to the type checking provided by TypeScript.

gistlibby LogSnag