Remove empty fields from an object

    Object.keys(obj).forEach(key => (obj[key] === undefined || obj[key] === null || obj[key] === "") && delete obj[key])
  

Query with headers, params and body

  async function fetchData() {
  const url = 'https://example.com/api';

  const headers = new Headers({
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YourAccessTokenHere', // Include any necessary headers
  });

  const params = new URLSearchParams({
    key1: 'value1',
    key2: 'value2',
  });

  const urlWithParams = `${url}?${params}`;

  const requestBody = {
    key: 'value',
    anotherKey: 'anotherValue',
  };

  const requestOptions: RequestInit = {
    method: 'POST', // or 'GET', 'PUT', 'DELETE', etc.
    headers: headers,
    body: JSON.stringify(requestBody),
  };

  try {
    const response = await fetch(urlWithParams, requestOptions);

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}

fetchData();
  

Forms

Here’s a basic form submission. Notice React.FormEvent and new FormData(form)

  async function handleAdd(e: React.FormEvent) {
    e.preventDefault()

    const form = e.target as HTMLFormElement
    const data = new FormData(form)
    const title = data.get("title")

    if(typeof(title) === "string" && title.length > 0) {

    }
}
  

Convert React to TypeScript

Step 1/6

Install dev dependencies

  yarn add -D typescript @types/react @types/react-dom
  

Step 2/6

In packages.json, replace:

  "build": "vite build"
  

With 👇

  "build": "tsc && vite build"
  

Step 3/6

Rename vite.config.js and main.jsx to vite.config.ts and main.tsx

Step 4/6

Configure TypeScript by creating these two files in the root of your project:

tsconfig.json

  {
	"compilerOptions": {
		"target": "ESNext",
		"useDefineForClassFields": true,
		"lib": ["DOM", "DOM.Iterable", "ESNext"],
		"allowJs": false,
		"skipLibCheck": true,
		"esModuleInterop": false,
		"allowSyntheticDefaultImports": true,
		"strict": true,
		"forceConsistentCasingInFileNames": true,
		"module": "ESNext",
		"moduleResolution": "Node",
		"resolveJsonModule": true,
		"isolatedModules": true,
		"noEmit": true,
		"jsx": "react-jsx"
	},
	"include": ["src"],
	"references": [{
		"path": "./tsconfig.node.json"
	}]
}
  

tsconfig.node.json

  {
	"compilerOptions": {
		"composite": true,
		"module": "ESNext",
		"moduleResolution": "Node",
		"allowSyntheticDefaultImports": true
	},
	"include": ["vite.config.ts"]
}

**Step 5/6**

Create a file named `vite-env.d.ts` inside the `src/` folder and copy and paste this (with the three slashes at the beginning):

NoneBashCSSCC#ElixirErlangGoGraphQLGroovyHaskellHCLHTMLINIJavaJavaScriptJSONJSXKotlinLispLuaMermaid DiagramNixObjective-COCamlPerlPHPPowershellPythonRubyRustScalaSQLSoliditySwiftTOMLTSXTypeScriptVisual BasicYAMLZigCopy
  

///

  
**Step 6/6**

In your `index.html` you should change the name of your script from the old `main.jsx` to `main.tsx` like this:

NoneBashCSSCC#ElixirErlangGoGraphQLGroovyHaskellHCLHTMLINIJavaJavaScriptJSONJSXKotlinLispLuaMermaid DiagramNixObjective-COCamlPerlPHPPowershellPythonRubyRustScalaSQLSoliditySwiftTOMLTSXTypeScriptVisual BasicYAMLZigCopy
  
  
That's it. Happy coding 🙂

## Object properties
```javascript
const buttonSvg: Record<number, React.ReactNode> = {
        0: <svg>hi</svg>