ReasonJun

Typescript : type (any / unknown / Tuple / Void / Never / Union / Intersection) 본문

Frontend/Typescript

Typescript : type (any / unknown / Tuple / Void / Never / Union / Intersection)

ReasonJun 2023. 6. 10. 00:41
728x90
/// Any
// All types are possible. However, in this case, there is no reason to use typescript, so it is rarely used.
let hello3: any = 'Hello world'
hello3 = 123
hello3 = false
hello3 = null
hello3 = {}
hello3 = []
hello3= function () {}

/// Unknown
const z: any = 123
const u: unknown = 123

// When z is changed to u, all errors occur except for 'any'.
// In other words, it is better to use 'unknown' rather than 'any'.
const any: any = z
const boo: boolean = z
const num2: number = z
const arr1: string[] = z
const obj1: { x: string, y:number } = z

/// Tuple
const tuple: [string, number, boolean] = ['a', 1, false]
// The difference from array is that it must have the same shape as set in tuple.
const users: [number, string, boolean] []
    = [[1, 'NEO', true], [2, 'Evan', false], [3, 'Lewis', true]]

/// Void
// When a function has no return value, it must be set to void.
function hallo(msg: string): void {
    console.log(`Hello ${msg}`)
}

function hallo1(msg: string): undefined {
    console.log(`Hello ${msg}`)
    return undefined
}

/// Never
// a value that will never happen
const nev: [] = []
// nev.push(3) >>> error

/// Union
let union1: string | number
union1 = 'Hello type'
union1 = 123
// union1 = false >>> error 

let union2: (string | number | boolean) []

/// Intersection
interface User1 {
    name: string, 
    age: number
}
interface Validation {
    isValid: boolean
}
const heropy: User & Validation = {
    name: 'Neo',
    age: 85,
    isValid: true
}

Difference between any and unknown

  • any: The any type essentially turns off all type checking for a particular value or expression. It allows you to assign values of any type to variables of type any and perform any operations on them without type errors. The use of any removes the benefits of TypeScript's static type checking and essentially reverts the behavior back to regular JavaScript.
  • unknown: The unknown type is safer than any because it requires type checks and explicit type assertions before performing certain operations. You cannot assign values of type unknown to variables of other types without a type assertion or a type check. This enforces that you handle the type safely and explicitly narrow down the type before performing operations that are specific to that type.
728x90

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

Typescript : Assertion  (0) 2023.06.10
Typescript : Inference  (0) 2023.06.10
Typescript : Type Annotations (Variable, Function Return, Object Type )  (0) 2023.06.10
Typescript : Type  (0) 2023.06.09
Typescript : Concept  (0) 2023.06.09
Comments