ReasonJun

Typescript : Type Annotations (Variable, Function Return, Object Type ) 본문

Frontend/Typescript

Typescript : Type Annotations (Variable, Function Return, Object Type )

ReasonJun 2023. 6. 10. 00:41
728x90

Type annotations in TypeScript are used to explicitly specify the type of a variable, function parameter, return value, or any other entity in your code. They provide a way to declare the expected types and enforce type checking at compile-time, allowing you to catch type-related errors early in the development process. Type annotations are written using a syntax that resembles JavaScript, but with additional type information.

 

Here are some examples of type annotations in TypeScript:

  • Variable Type Annotations: You can annotate the type of a variable using the colon (:) followed by the desired type. For example:
/// string
let str: string
let red: string = "Red"
let green: string = 'Green'
let myColor: string = `My color is ${red}.`
let yourColor: string = 'Your color is' + green



/// number
let num: number
let integer: number = 6
let float: number = 3.14
let infinity: number = Infinity
let nan: number = NaN




/// boolean
let isBoolean: boolean
let isDone: boolean = false


/// Null / Undefined
let nul: null
// No data entered.
let und: undefined
// It contains data called undefined.
nul = null
console.log(nul)
// nul needs to be initialized separately as above. Only null is possible. 
// But, it is unnecessary, so this method is rarely used.
console.log(und)

In the above code, the type annotations : string, : number, and : boolean explicitly specify the types of the variables name, age, and isValid, respectively.

  • Function Parameter Type Annotations: You can annotate the types of function parameters to specify the expected types of the arguments passed to the function. For example:
function greet(name: string): void {
  console.log(`Hello, ${name}!`);
}

In this code, the name parameter of the greet function is annotated with the type string, indicating that it should receive a string argument.

  • Function Return Type Annotations: You can annotate the return type of a function to specify the expected type of the value returned by the function. For example:
function add(a: number, b: number): number {
  return a + b;
}


const add: (x: number, y: number) => number = function (x, y) {
    return x + y
}

const a: number = add(1,2)
// An error occurs when number is converted to a string.


const Hello: () => void = function () {
    console.log('Hello world~')
}
const Hello1 = function (): void {
    console.log('Hello world~')
}

// In the case above, javascript returns undefined, but typescript returns void.

In this code, the return type of the add function is annotated with the type number, indicating that it should return a value of type number.

  • Object Type Annotations: You can annotate the types of object properties using type annotations. For example:
/// object
// typeof DATA === 'object'
const obj: object = {}
const arr: object = []
const func: object = function () {}

interface User {
    name: string
    age: number
    isValid: boolean
}

const userA: User = {
    name: 'Heropy',
    age: 85,
    isValid: true
}

const userB: {
    name: string
    age: number
    isValid: boolean
} = {
    name: 'Neo',
    age: 22,
    isValid: false
}


/// array
const fruits: string[] = ['Apple', 'Banana', 'Cherry']
const numbers: number[] = [1, 2, 3, 4, 5, 6]
const union: (string|number) [] = ['Apple', 1, 2, 'Banana', 3]
// const array: [] = [1,2,3] >>> error

In this code, the person variable is annotated with an object type that specifies the types of the name and age properties.

 

Type annotations help TypeScript perform static type checking, which means that the TypeScript compiler analyzes your code and checks if the types used are compatible with the declared types. It can catch type-related errors, such as assigning a value of the wrong type to a variable or passing incorrect arguments to a function, before your code runs.

 

In addition to explicit type annotations, TypeScript also supports type inference, which allows it to automatically infer types based on the context. This means that in many cases, you don't have to explicitly annotate types, as TypeScript can deduce them from the code.

 

Type annotations in TypeScript provide a powerful mechanism for specifying types and enabling static type checking, helping to prevent type-related bugs and improve the maintainability and reliability of your codebase.

728x90

'Frontend > Typescript' 카테고리의 다른 글

Typescript : Assertion  (0) 2023.06.10
Typescript : Inference  (0) 2023.06.10
Typescript : type (any / unknown / Tuple / Void / Never / Union / Intersection)  (0) 2023.06.10
Typescript : Type  (0) 2023.06.09
Typescript : Concept  (0) 2023.06.09
Comments