`is` 키워드는 타이프 스크립트에서 무엇을합니까?
다음과 같은 코드를 발견했습니다.
export function foo(arg: string): arg is MyType {
return ...
}
나는 is
문서 나 구글에서 검색 할 수 없었다 . 꽤 흔한 단어이며 기본적으로 모든 페이지에 나타난다.
그 맥락에서 키워드는 무엇을합니까?
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”);
위의 형식에서 "test is string"형식 술어를 사용하면 (반환 유형에 부울을 사용하는 대신) isString ()이 호출 된 후 함수가 true를 반환하면 TypeScript는 a가 보호하는 모든 블록에서 유형을 문자열로 좁 힙니다. 함수를 호출합니다. 컴파일러는 foo가 아래 보호 된 블록의 문자열이라고 생각합니다 (그리고 아래 보호 된 블록에서만).
{
console.log(“it is a string” + foo);
console.log(foo.length); // string function
}
타입 술어는 컴파일 타임에만 사용됩니다. 결과 .js 파일 (런타임)은 TYPE을 고려하지 않기 때문에 차이가 없습니다.
아래 네 가지 예에서 차이점을 설명하겠습니다.
예 1 : 위의 예제 코드에는 컴파일 오류 및 런타임 오류가 없습니다.
예 2 : TypeScript가 유형을 문자열로 좁히고 toExponential이 문자열 메서드에 속하지 않는지 확인했기 때문에 아래 예제 코드에는 컴파일 오류 (및 런타임 오류)가 있습니다.
function example(foo: any){
if(isString(foo)){
console.log(“it is a string” + foo);
console.log(foo.length);
console.log(foo.toExponential(2));
}
}
예 3 : 아래 예제 코드에는 컴파일 오류가 없지만 TypeScript가 보호되는 블록의 문자열로만 유형을 좁히기 때문에 런타임 오류가 발생하므로 foo.toExponential은 컴파일 오류를 생성하지 않습니다 (TypeScript는 문자열 유형). 그러나 런타임에서 string에는 toExponential 메서드가 없으므로 런타임 오류가 발생합니다.
function example(foo: any){
if(isString(foo)){
console.log(“it is a string” + foo);
console.log(foo.length);
}
console.log(foo.toExponential(2));
}
E.g. 4: if we don’t use “test is string” (type predicate), TypeScript will not narrow the type in the block guarded and the below example code will not have compile error but it will have runtime error.
function isString(test: any): boolean{
return typeof test === “string”;
}
function example(foo: any){
if(isString(foo)){
console.log(“it is a string” + foo);
console.log(foo.length);
console.log(foo.toExponential(2));
}
}
The conclusion is that “test is string” (type predicate) is used in compile time to tell the developers the code will have chance to have runtime error. For javascript, the developers will not KNOW the error in compile time. This is the advantage of using TypeScript.
The only use I know is the one of your example: specifying a "type predicate" (arg is MyType
) in an user defined Type Guard
See User Defined Type Guards in this reference
Here is another reference
ReferenceURL : https://stackoverflow.com/questions/40081332/what-does-the-is-keyword-do-in-typescript
'UFO ET IT' 카테고리의 다른 글
자바에서 호출자 클래스를 얻는 방법 (0) | 2021.01.09 |
---|---|
파이썬의 문자열에서 ANSI 이스케이프 시퀀스를 제거하는 방법 (0) | 2021.01.09 |
네트워크 중단 후 자동으로 (또는 더 쉽게) 화면 세션에 다시 연결 (0) | 2021.01.08 |
C #에 Dictionary <>와 같은 클래스가 있지만 키에만 값이 없습니까? (0) | 2021.01.08 |
루트가 아닌 권한으로 추적 된 명령을 실행하기 위해 dtrace를 얻으려면 어떻게해야합니까? (0) | 2021.01.08 |