문자열의 유형 확장
7212 단어 typescript
문제
type Roles = "student" | "teacher";
type Person = {
role: Roles;
name: string;
age: number;
}
function doSomethingWithPerson(person: Person) {
console.log(person);
}
const andy = {
role: "teacher",
name: "andy",
age: 31
};
doSomethingWithPerson(andy); //Argument of type '{ role: string; name: string; age: number; }' is not assignable to parameter of type 'Person'.
Playground Link
이 코드는 오류를 생성합니다.
Argument of type '{ role: string; name: string; age: number; }' is not assignable to parameter of type 'Person'.
Types of property 'role' are incompatible.
Type 'string' is not assignable to type 'Roles'.
무슨 일이야?
우리가 선언한 andy 객체가 함수가 원하는 유형Person과 일치하는데 TypeScript가 불평하는 이유는 무엇입니까?
빠른 솔루션
문자열 선언 "teacher" as const
const andy = {
role: "teacher" as const,
name: "andy",
age: 31
};
doSomethingWithPerson(andy);
설명
이 시나리오에서 객체 andy를 선언하면 TypeScript는 role 속성의 유형을 string , 모든 문자열로 유추합니다!
"teacher" 및 "student"는 문자열이지만 문자열의 하위 집합입니다.
Person 유형은 문자열을 원하지 않고 두 개의 특정 문자열만 원합니다.
TypeScript는 string가 type widening이라고 불리는 것이 아니라 "teacher"로 유형을 유추합니다.
TypeScript가 하는 일은 나중에 다음과 같은 코드를 작성할 수 있도록 합니다.
andy.role = "foobar";
(즉, andy 개체를 변경하고 있습니다).
as const 키워드가 하는 일은 유형 확장을 방지하는 것입니다. See the documentation here .
당신이 하고 있는 것은 TypeScript에 '걱정하지 마세요. 이 속성을 재할당하지 않을 것이라고 약속합니다'라고 말하는 것입니다. 시도하면 TypeScript에서 오류가 발생합니다.
const andy = {
role: "teacher" as const,
name: "andy",
age: 31
};
andy.role = "foobar"; //Type '"foobar"' is not assignable to type '"teacher"'.(2322)
대체 솔루션
문자열 선언 "teacher" as "teacher"
const andy = {
role: "teacher" as "teacher",
name: "andy",
age: 31
};
doSomethingWithPerson(andy);
이것은 유형 확장을 방지하기 위해 as const 키워드를 사용하는 대신 role 속성의 유형을 "teacher" 로 명시적으로 설정합니다.
as const 및 as "teacher" 모두 동일한 최종 효과를 가지며 role 속성 유형은 "teacher" 입니다.
Reference
이 문제에 관하여(문자열의 유형 확장), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://dev.to/dwjohnston/type-widening-on-strings-4i99
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
type Roles = "student" | "teacher";
type Person = {
role: Roles;
name: string;
age: number;
}
function doSomethingWithPerson(person: Person) {
console.log(person);
}
const andy = {
role: "teacher",
name: "andy",
age: 31
};
doSomethingWithPerson(andy); //Argument of type '{ role: string; name: string; age: number; }' is not assignable to parameter of type 'Person'.
Argument of type '{ role: string; name: string; age: number; }' is not assignable to parameter of type 'Person'.
Types of property 'role' are incompatible.
Type 'string' is not assignable to type 'Roles'.
문자열 선언
"teacher" as constconst andy = {
role: "teacher" as const,
name: "andy",
age: 31
};
doSomethingWithPerson(andy);
설명
이 시나리오에서 객체 andy를 선언하면 TypeScript는 role 속성의 유형을 string , 모든 문자열로 유추합니다!
"teacher" 및 "student"는 문자열이지만 문자열의 하위 집합입니다.
Person 유형은 문자열을 원하지 않고 두 개의 특정 문자열만 원합니다.
TypeScript는 string가 type widening이라고 불리는 것이 아니라 "teacher"로 유형을 유추합니다.
TypeScript가 하는 일은 나중에 다음과 같은 코드를 작성할 수 있도록 합니다.
andy.role = "foobar";
(즉, andy 개체를 변경하고 있습니다).
as const 키워드가 하는 일은 유형 확장을 방지하는 것입니다. See the documentation here .
당신이 하고 있는 것은 TypeScript에 '걱정하지 마세요. 이 속성을 재할당하지 않을 것이라고 약속합니다'라고 말하는 것입니다. 시도하면 TypeScript에서 오류가 발생합니다.
const andy = {
role: "teacher" as const,
name: "andy",
age: 31
};
andy.role = "foobar"; //Type '"foobar"' is not assignable to type '"teacher"'.(2322)
대체 솔루션
문자열 선언 "teacher" as "teacher"
const andy = {
role: "teacher" as "teacher",
name: "andy",
age: 31
};
doSomethingWithPerson(andy);
이것은 유형 확장을 방지하기 위해 as const 키워드를 사용하는 대신 role 속성의 유형을 "teacher" 로 명시적으로 설정합니다.
as const 및 as "teacher" 모두 동일한 최종 효과를 가지며 role 속성 유형은 "teacher" 입니다.
Reference
이 문제에 관하여(문자열의 유형 확장), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://dev.to/dwjohnston/type-widening-on-strings-4i99
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
andy.role = "foobar";
const andy = {
role: "teacher" as const,
name: "andy",
age: 31
};
andy.role = "foobar"; //Type '"foobar"' is not assignable to type '"teacher"'.(2322)
문자열 선언
"teacher" as "teacher"const andy = {
role: "teacher" as "teacher",
name: "andy",
age: 31
};
doSomethingWithPerson(andy);
이것은 유형 확장을 방지하기 위해
as const 키워드를 사용하는 대신 role 속성의 유형을 "teacher" 로 명시적으로 설정합니다.as const 및 as "teacher" 모두 동일한 최종 효과를 가지며 role 속성 유형은 "teacher" 입니다.
Reference
이 문제에 관하여(문자열의 유형 확장), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/dwjohnston/type-widening-on-strings-4i99텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)