ReasonJun

Typescript : Assertion 본문

Frontend/Typescript

Typescript : Assertion

ReasonJun 2023. 6. 10. 01:12
728x90

In TypeScript, assertion (also known as type assertion or type casting) is a way to inform the TypeScript compiler about the type of a value when the compiler cannot infer it automatically. It allows you to override the default type inference and treat a value as a specific type, even if there is no obvious relationship between the original type and the asserted type.

 

Type assertions are typically used in situations where you, as the developer, have more knowledge about the type of a value than TypeScript can determine statically. It is a way to instruct the compiler to trust your judgment regarding the type of the value.

 

There are two syntaxes for performing type assertions in TypeScript:

// type assertion

// assert keyword - as

// In situations 1 and 2, type guards are the most ideal. This is because it allows the program to know on its own, rather than a human specifying that a variable has data. So you can prevent any errors.

//* 1)
const el = document.querySelector('body') as HTMLBodyElement;
// el can be null.
// So, if you are sure that there is, if you declare it as above, you can get rid of the error that occurs because it can be null data.
el.textContent = 'hello';

//* 1-1)
const el1 = document.querySelector('body');
el1!.textContent = 'hello';

//* 1-2) type guard
if (el) {
  el.textContent = 'hello';
}

//* 2)
function getNumber(x: number | null | undefined) {
  return Number((x as number).toFixed(2));
}
getNumber(null); // error

//* 2-1)
function getNumber1(x: number | null | undefined) {
  return Number(x!.toFixed(2));
}
getNumber1(null); // error

//* 2-2) type guard
function getNumber2(x: number | null | undefined) {
  if (x) {
    return Number(x.toFixed(2));
  }
}
getNumber2(null);

//* 3)
function getValue(x: string | number, isNumber: boolean) {
  if (isNumber) {
    return Number((x as number).toFixed(2));
  }
  return (x as string).toUpperCase();
}

getValue('hello', false); // HELLO
getValue(3.141592, true); // 3.14

// Assertion

let numm: number;
//! console.log(numm) error
let numun!: number;
console.log(numun); // undefined

It's important to note that type assertions do not perform any runtime type checking or conversion. They are purely a way to provide hints to the TypeScript compiler for type checking during the compilation process. If the type assertion is incorrect and the runtime value does not match the asserted type, runtime errors may occur.

 

 

Definite assignment assertion

If you declare 'public props = {} as Props', the error is made when a result is an empty object.

It is not initialized, but it is declared as if it has been initialized by assigning '!'.

 

The ! symbol is called a definite assignment assertion. It tells the TypeScript compiler that the property will be assigned a value before it is used, even if the property is nullable or undefined. It allows you to bypass the usual strict null checks and let the compiler know that you'll handle the initialization of the property yourself.

 

Here's an example to illustrate its usage:

interface Props {
  name: string;
  age: number;
}

class Person {
  props!: Props;

  constructor(name: string, age: number) {
    this.props = { name, age };
  }

  sayHello() {
    console.log(`Hello, my name is ${this.props.name} and I'm ${this.props.age} years old.`);
  }
}

const john = new Person("John", 25);
john.sayHello(); // Output: Hello, my name is John and I'm 25 years old.

In this example, the props property is declared with the ! assertion, indicating that it will be assigned a value before it is accessed in the sayHello() method. The constructor assigns a value to props during object initialization, ensuring that it won't be undefined or null when used later.

 

It's important to note that using the definite assignment assertion (!) should be done with caution. It should only be used when you're confident that the property will be assigned a value before it's accessed, as it bypasses the compiler's strict null checks.

728x90
Comments