Page cover image

πŸ–¨οΈTypescript

In typescript global types can be declared in a .d.ts file and used anywhere without explicitly importing them. Our project's .d.ts file is named project.d.ts .

It contains:

  1. Some library types in the form of [triple slash directives](https: //www.typescriptlang.org/docs/handbook/triple-slash-directives.html). These need to be placed at the top of the file.

  2. Some library module declarations (usually these are included because these libs don't have typings but we still need to use them).

  3. Our own global types.

Typescript provides many [Utility Types](https: //www.typescriptlang.org/docs/handbook/utility-types.html) which are useful for manipulating the base types in the global ComponentTypes interface.

A few basic ones to know:

Pick<Type, Keys>

Only use the specified Keys from the Type.

Pick<ComponentTypes, "text">;

// only use 'text' type

Partial<Type>

Allows the type to be optional (undefined)

Partial<Pick<ComponentTypes, "text">>;

// only use 'text' type

// the text type is optional

Required<Type>

Opposite of Partial, the type must be defined

Required<Pick<ComponentTypes, "text">>;

// only use 'text' type

// the text type is required

Using the stategies above you can select types from the global source and compose them to create a representation of the props in a specific component. While the global types live in project.d.ts , component level types should generally be placed in a types.ts file within the component directory and imported for use.

Although ComponentTypes is a βœ… _Good starting place, some components may require a type that is more specific and not usefully included in the global declaration._


Naming

  • {['class', 'enum', 'interface', 'namespace', 'type', 'variable-and-function'].map(item => (

  • {item.split('-').join(' ')}

  • ))}


class

πŸ§‘β€πŸ”¬ PascalCase

🚫 Bad

class foo {}

βœ… Good

class Foo {}

For memebers/methods use πŸͺ camelCase

🚫 Bad

class Foo {
  Bar: number;
  BazQux() {}
}

βœ… Good

class Foo {
  bar: number;
  bazQux() {}
}

enum

πŸ§‘β€πŸ”¬ PascalCase

🚫 Bad

enum backgroundColor {}

βœ… Good

enum BackgroundColor {}

interface

πŸ§‘β€πŸ”¬ PascalCase

🚫 Bad

interface checkboxProps {}

βœ… Good

interface CheckboxProps {}

For memebers use πŸͺ camelCase

🚫 Bad

interface CheckboxProps {
  IsSelected: boolean;
}

βœ… Good

interface CheckboxProps = {
  isSelected: boolean;
}

namespace

πŸ§‘β€πŸ”¬ PascalCase

🚫 Bad

namespace foo {}

βœ… Good

namespace Foo {}

type

πŸ§‘β€πŸ”¬ PascalCase

🚫 Bad

type imageProps = { src: string; alt: string };

βœ… βœ… Good

type ImageProps = { src: string; alt: string };

variable and function

πŸͺ camelCase

🚫 Bad

const FooBar = "baz";

const FooBar = () => "baz";

βœ… Good

const fooBar = "baz";

const fooBar = () => "baz";

React | Typescript | Tailwind | Forms | Unit Tests

Last updated

Was this helpful?