Skip to content

Instantly share code, notes, and snippets.

@misostack
Last active February 19, 2023 13:01
Show Gist options
  • Save misostack/697ae8274dc201d80ac0416210694492 to your computer and use it in GitHub Desktop.
Save misostack/697ae8274dc201d80ac0416210694492 to your computer and use it in GitHub Desktop.
typescript cheatsheet

Typescript CheatSheet

1. How to fix "No initializer and is not definitely assigned in the constructor" error ?

Let's see this example

image

Property 'description' has no initializer and is not definitely assigned in the constructor.

There are 3 ways:

  • You can define default value for description when define this property. Eg: description: string = '';
  • You can use exclaimation point ( ! ). Eg description!: string;
  • You can set the default value for description in constructor function
class Example {
  title: string;
  createdAt: Date;
  updatedAt: Date;
  description!: string;

  constructor(title: string) {
    this.title = title;
    const now = new Date();
    this.createdAt = now;
    this.updatedAt = now;
  }
}

ReactJS Cheatsheet

1.How to fix "missing in props validation" in ReactJS ?

2.How to fix "Property 'propTypes' does not exist on type 'typeof'" in ReactJS?

The reason is missing type definition for PropTypes. So you need to add a static property

3. How to fix "type is not assignable to type intrinsic attribute" ?

All you need is to declare the component type properly to include the props type:

npm i prop-types
npm i @types/prop-types --save-dev
import React from 'react';
import PropTypes from 'prop-types';
import { Example } from './StateExample';

interface PropExampleProps {
  example: Example;
}

export class PropExample extends React.Component<PropExampleProps> {
  public static propTypes = {};
  constructor(props: { example: Example }) {
    super(props);
    this.state = {
      example: props.example
    };
  }

  render() {
    const { example } = this.state as { example: Example };
    return (
      <>
        <p>{example.toString()}</p>
      </>
    );
  }
}

PropExample.propTypes = {
  example: PropTypes.any
};

4. Compare between Type and Interface

image

@misostack
Copy link
Author

image
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment