클래스나 함수가 사용될 때 타입을 설정합니다
타입 검사를 요구합니다
const color = 'blue'
const color: string = 'blue
const list: number[] = [1, 2, 3]
Array<elemType>
const list: Array<number> = [1, 2, 3]
튜플 타입을 사용하려면 순서를 맞춰줘야 에러가 나지 않습니다
// 튜플 타입으로 선언
let x: [string, number];
// 초기화
x = ["hello", 10]; // 성공
// 잘못된 초기화
x = [10, "hello"]; // 오류
//접근방식
console.log(x[0]. );
기본적으로, enum은 0부터 시작하여 멤버들의 번호를 매깁니다.
멤버 중 하나의 값을 수동으로 설정하여 번호를 바꿀 수 있습니다.
enum Color {Red, Green, Blue}
=>
enum Color {Red = 1, Green = 2, Blue = 4}
const colorName: string = Color[2];
console.log(colorName); // 값이 2인 'Green'이 출력됩니다.
정확하지 않은 타입을 표현해야 할 수도 있는데, 이런 경우에는 타입 검사를 하지 않습니다
const a: any = ''
const list: any[] = [...]
let u: undefined = undefined;
let n: null = null;
// never를 반환하는 함수는 함수의 마지막에 도달할 수 없다.
function error(message: string): never {
throw new Error(message);
}
// 반환 타입이 never로 추론된다.
function fail() {
return error("Something failed");
}
// never를 반환하는 함수는 함수의 마지막에 도달할 수 없다.
function infiniteLoop(): never {
while (true) {
}
}
declare function create(o: object | null): void;
create({ prop: 0 }); // 성공
create(null); // 성공
create(42); // 오류
create("string"); // 오류
create(false); // 오류
create(undefined); // 오류
const someValue: any = "this is a string";
const strLength: number = (<string>someValue).length;
const someValue: any = "this is a string";
const strLength: number = (someValue as string).length;