is

먼저 Arrray.isArray 메서드를 보면

const what: unknown = '?';

if (Array.isArray(what)) {
  what.pop();
}

unknown 타입이지만 if문을 통과하게 되면 pop이라는 메서드를 사용할 수 있게 된다.

이는 isArray() 메서드를 보면 알 수 있다.

interface ArrayConstructor {
		...
    isArray(arg: any): arg is any[];
		...
}

isArray가 반환하는 타입을 보면 arg is any[]임을 알 수 있는데, is 덕분에 array 메서드를 사용할 수 있는것이다.

function isString(test: any): test is string{
    return typeof test === "string";
}

function example(foo: any){
    if(isString(foo)){
        console.log("it is a string" + foo);
        console.log(foo.length); // string function
    }
}
example("hello world");

isString함수에서 return 문의 값이 true일 때, test is string이라는 type predicate구문이 있기 때문에 타입스크립트는 이 함수를 호출한 범위 내에서 isString의 결과 타입을 string로 좁힐 수 있다.

결국, 함수가 호출된 범위 내에선 test를 string 타입으로 보라는 것이다.

컴파일 단계에서 사용되며 런타입 단계에서는 순수한 js파일과 동일하게 동작한다.

as

컴파일 단계에서 타입 검사를 할 때 타입스크립트가 감지하지 못하는 애매한 타입요소들을 직접 명시해주는 키워드라고 볼 수 있다.

as는 수동으로 컴파일러에게 타입 힌트를 주는 것이라 생각하면 편할 것 같다.