programing

TypeScript에서 연산자를 사용하는 이유는 무엇입니까?

showcode 2023. 6. 9. 22:10
반응형

TypeScript에서 연산자를 사용하는 이유는 무엇입니까?

이 경우 TypeScript에서 연산자를 사용해야 하는 이유는 무엇입니까?

type Species = "cat" | "dog";


interface Pet {
   species: Species
}

interface Cat extends Pet {

}

function petIsCat(pet: Pet): pet is Cat {
   return pet.species === "cat";
}

사용해야 하는 이유pet is Cat대신boolean만약 몸이 쿨 타입으로 돌아온다면요?

boolean은 데이터 형식일 뿐이고 'is' 연산자는 형식 지정에 사용됩니다.예를 조금 바꿔 보겠습니다.

type Species = 'cat' | 'dog';

interface Pet {
    species: Species;
}

class Cat implements Pet {
    public species: Species = 'cat';
    public meow(): void {
        console.log('Meow');
    }
}

function petIsCat(pet: Pet): pet is Cat {
    return pet.species === 'cat';
}

function petIsCatBoolean(pet: Pet): boolean {
    return pet.species === 'cat';
}

const p: Pet = new Cat();

p.meow(); // ERROR: Property 'meow' does not exist on type 'Pet'.

if (petIsCat(p)) {
    p.meow(); // now compiler knows for sure that the variable is of type Cat and it has meow method
}

if (petIsCatBoolean(p)) {
    p.meow(); // ERROR: Property 'meow' does not exist on type 'Pet'.
}

물론 유형 주조를 사용할 수 있습니다.

(<Cat>p).meow(); // no error
(p as Cat).meow(); // no error

하지만 그것은 시나리오에 따라 다릅니다.

제가 이해하는 방법은 다음과 같습니다.

애완동물은 고양이입니다.

  • 함수 반환 유형입니다.
  • 그것은 "사용자 정의 유형 검사" 구문을 가지고 있기 때문에 사용자 정의 유형 검사라고 불립니다.
  • 이 함수 반환 유형은 컴파일 시 코드 "type-checker"에서 사용할 수 있습니다. 따라서 TS용 유형 검사 소프트웨어가 장착된 코드 편집기에서 컴파일 오류가 0개 표시되고 사용자 정의 유형 가드 다음에 person1의 유형을 알 수 있습니다.
const isPerson = (object: any): object is Person => "address" in object

interface Person {
    address: string
}
// type of person1 is {address: string}
const person1 = {
    address: "rue"
}

if(isPerson(person1)){
    console.log(person1.address) // type is Person as opposed to {address: string}
} else {
    console.log("person is not a Person")
}

도움이 되길 바랍니다.

언급URL : https://stackoverflow.com/questions/51124837/what-is-reason-to-use-is-operator-in-typescript

반응형