ReasonJun

Typescript : When I use 'type annotation', 'type inference', 'type assertion' in typescript 본문

Frontend/Typescript

Typescript : When I use 'type annotation', 'type inference', 'type assertion' in typescript

ReasonJun 2023. 6. 17. 16:51
728x90

If typescript cannot infer the type and need to do type annotation

1. In case of unilaterally returning any type

const json = '{"x": 1, "y": 2}';
const coordinates = JSON.parse(json);
console.log(coordinates);

2. If you declare a variable first and initialize it later => In this case, it is inferred as any.

let greeting
greeting = 'hello' // let greeting: any

3. When the value to be assigned to a variable is not constant

let num = [-7, -2. -10]
let numAboveZero: boolean | number = false

for (let i = 0; i < num.length; i++) {
	if(num[i]> 0) {
		numAboveZero = num[i]
	}
}

When to use type annotations

  • When you want to provide more precise type information to the TypeScript compiler. This can help to prevent errors and to provide better error messages.
  • When you want to make your code more readable and maintainable. Type annotations can help to document the types of variables and expressions, which can make it easier for other developers to understand your code.

When to use type inference

  • When the type of a variable or expression is obvious. For example, if you initialize a variable with a string literal, you can use type inference to let TypeScript infer that the variable is a string.
  • When you want to make your code more concise. Type inference can help to make your code more concise by removing the need to explicitly specify the types of variables and expressions.

Which one should I use?

In general, it is a good practice to use type annotations whenever possible. This will help to provide more precise type information to the TypeScript compiler and to make your code more readable and maintainable. However, type inference can be used to make code more concise, especially when the type of a variable or expression is obvious.

 

When to use type assertion

  • Force the TypeScript compiler to treat a variable or expression as a certain type. This can be useful for working with code that is not well-typed or that is coming from an external source.
  • Provide more precise type information to the TypeScript compiler. This can help to prevent errors and to provide better error messages.
  • Make your code more readable and maintainable. By explicitly specifying the type of a variable or expression, you can help to make your code easier to understand for other developers.

It is important to note that type assertions do not actually change the type of a variable or expression. They simply tell the TypeScript compiler to treat the variable or expression as a certain type for the purposes of type checking.

728x90
Comments