타이프스크립트:사용자 지정 유형에 대해 "type of" 확인
커스텀 타입이 있습니다.
export type Fruit = "apple" | "banana" | "grape";
스트링이 과일 타입인지 아닌지 판단하고 싶습니다.어떻게 하면 좋을까요?
다음 항목은 작동하지 않습니다.
let myfruit = "pear";
if (typeof myfruit === "Fruit") {
console.log("My fruit is of type 'Fruit'");
}
아무쪼록 잘 부탁드립니다!
간단한 답변:
사용할 수 없습니다.typeof체크할 런타임에interface타입. 컴파일 시에만 존재합니다.대신 사용자 정의 유형 가드 함수를 작성하여 다음과 같은 유형을 확인할 수 있습니다.
const fruit = ["apple", "banana", "grape"] as const;
type Fruit = (typeof fruit)[number];
const isFruit = (x: any): x is Fruit => fruit.includes(x);
let myfruit = "pear";
if (isFruit(myfruit)) {
console.log("My fruit is of type 'Fruit'");
}
장황한 답변은 다음과 같습니다.
TypeScript의 값과 타입의 차이에 대해 혼란스러울 수 있습니다.특히 TypeScript는typeof교환입니다.아시다시피 TypeScript는 JavaScript에 정적 유형 시스템을 추가하며, 코드가 변환되면 해당 유형 시스템이 지워집니다.TypeScript의 구문은 일부 식과 문은 런타임에 존재하는 값을 참조하고 다른 식과 문은 설계/컴파일 시에만 존재하는 유형을 참조하도록 되어 있습니다.값에는 유형이 있지만 유형 자체는 아닙니다.중요한 것은 코드 내에 컴파일러가 값을 예상하여 가능한 경우 값을 검출한 식을 해석하는 장소와 컴파일러가 유형을 예상하여 가능한 경우 유형을 해석하는 장소가 있다는 것입니다.
그typeof오퍼레이터는 이중생활을 합니다.표현typeof x항상 기대하고 있다x가치가 있다typeof x컨텍스트에 따라 값 또는 타입이 될 수 있습니다.
let bar = {a: 0};
let TypeofBar = typeof bar; // the value "object"
type TypeofBar = typeof bar; // the type {a: number}
회선let TypeofBar = typeof bar;는 JavaScript에 접속하여 실행 시 JavaScript 타입의 연산자를 사용하여 문자열을 생성합니다.그렇지만type TypeofBar = typeof bar;는 지워지고 TypeScript type 쿼리 연산자를 사용하여 TypeScript가 지정한 값에 할당한 정적 유형을 검사합니다.bar.
당신의 코드로,
let myfruit = "pear";
if (typeof myfruit === "Fruit") { // "string" === "Fruit" ?!
console.log("My fruit is of type 'Fruit'");
}
typeof myfruit값은 타입이 아니라 값입니다.이게 바로 자바스크립트입니다.typeof연산자. TypeScript 유형 쿼리 연산자가 아닙니다.항상 값이 반환됩니다."string";그럴 일은 없을 것이다.Fruit또는"Fruit". 실행 시 TypeScript type 쿼리 연산자의 결과를 가져올 수 없습니다. 왜냐하면 Type system은 실행 시 지워지기 때문입니다.포기하셔야 합니다.typeof교환입니다.
할 수 있는 것은, 다음의 값을 체크하는 것입니다.myfruit알려진 세 사람과 맞서서Fruit★★★★★★★★★★★★...예를 들어 다음과 같습니다.
let myfruit = "pear";
if (myfruit === "apple" || myfruit === "banana" || myfruit === "grape") {
console.log("My fruit is of type 'Fruit'");
}
.여기 덜 중복된 방법이 있습니다. 자신의 「」, 「」를 합니다.Fruit'그' 입니다.TypeScript는 값에서 유형을 추론할 수 있지만 유형에서 값을 생성할 수는 없습니다.
const fruit = ["apple", "banana", "grape"] as const;
export type Fruit = (typeof fruit)[number];
해서 하실 수 .Fruit수동으로 정의한 것과 같은 타입입니다.그런 다음 유형 테스트에 다음과 같이 사용자 정의 유형 가드를 사용할 수 있습니다.
const isFruit = (x: any): x is Fruit => fruit.includes(x);
isFruit()가 이 함수에 여부를 입니다.fruit을 array로 .Fruit어디 한번 보자.
let myfruit = "pear";
if (isFruit(myfruit)) {
console.log("My fruit is of type 'Fruit'");
}
이 가드는 가 " 절 "then"이 있음을 .if 「」라고 하는 것,myfruit는 입니다.Fruit만 하는 해 보세요.Fruit에는 a,, , , no, no, no, no, no, no, , no, no, no, no, no, no, no, noFruit:
declare function acceptFruit(f: Fruit): void;
const myfruit = Math.random() < 0.5 ? "pear" : "banana";
함수를 직접 호출할 수 없습니다.
acceptFruit(myfruit); // error, myfruit might be "pear"
단, 체크 후 "then" 절 안에서 호출할 수 있습니다.
if (isFruit(myfruit)) {
acceptFruit(myfruit); // okay, myfruit is known to be "banana"
}
그래서 애초에 커스텀 타입과 대조하고 싶은 것이군요.그럼 할 수 있는 거네요.
요약: 사용할 수 없습니다.typeof비교할 수 문자열과 비교할 수 있습니다.중복된 코드를 제거하고 컴파일러에서 제어 흐름 유형 분석을 얻기 위해 몇 가지 유형 추론 및 유형 가드를 수행할 수 있습니다.
typeofTS:
typeofTS의 연산자는 2개의 다른 컨텍스트에서 사용할 수 있습니다.
- 식/값 컨텍스트에서 해당 유형의 문자열을 반환합니다.은 JavaScript일 입니다.
typeof이치노 - 유형을 기존 식/값과 유사하게 만드는 유형 컨텍스트.이것은 특정 타입에 대해 보다 쉽게 자신을 표현할 수 있도록 하기 위한 TS 구조입니다.컴파일되어 컴파일된 JavaScript에는 표시되지 않습니다.
예:
식/값 컨텍스트
const hi = 'hi';
const one = 1;
const obj = {};
console.log(typeof hi, typeof 1, typeof obj);
// [LOG]: "string", "number", "object"
유형 컨텍스트:
const obj1 = {foo: 1, bar: true};
const obj2 = {foo: 1, bar: ''};
// test has the type according to the structure of obj1
const test: typeof obj1 = {foo: 1, bar: true};
// typeof obj1 is the same as:
type sameAsTypeofObj1 = {foo: number, bar: string}
// test2 has the type according to the structure of obj1
const test2: typeof obj2 = {foo: 1, bar: true};
// In test2 we get a compile error since bar is not correct
// Since the type of obj2 is {foo: number, bar: string} we get the error:
// Type 'boolean' is not assignable to type 'string'
특정 문제에 대해서는 사용자 정의 타입 가드를 사용하는 것이 좋다고 생각합니다.다음은 예를 제시하겠습니다.
type Fruit = "apple" | "banana" | "grape";
let myfruit = "apple";
// user defined type guard
function isFruit(fruit: string): fruit is Fruit {
return ["apple", "banana", "grape"].indexOf("fruit") !== -1;
}
if (isFruit(myfruit)) {
// if this condition passes
// then TS compiler knows that myfruit is of the Fruit type
myfruit
}
언급URL : https://stackoverflow.com/questions/51528780/typescript-check-typeof-against-custom-type
'programing' 카테고리의 다른 글
| AngularJS - ng-Repeat 내의 속성 이름을 참조하려면 어떻게 해야 합니까? (0) | 2023.03.25 |
|---|---|
| express/node js에서 오류 http 응답을 보내는 방법 (0) | 2023.03.25 |
| 서버 127.0.0.1 셸/mongo에 연결할 수 없습니다.js (0) | 2023.03.25 |
| Import React 구문과 Import {Component } 구문의 차이 (0) | 2023.03.25 |
| Uncaughed TypeError: 정의되지 않은 속성(React-Router-Dom)을 읽을 수 없습니다. (0) | 2023.03.25 |