나는이 책 https://hamednourhani.gitbooks.io/typescript-book/타이프 라이터의 제어 흐름 분석
interface Square {
kind: "square";
size: number;
}
interface Rectangle {
kind: "rectangle";
width: number;
height: number;
}
interface Circle {
kind: "circle";
radius: number;
}
type Shape = Square | Rectangle | Circle;
//Type of function: function area1(s: Square | Rectangle | Circle): number | undefined
function area1(s: Shape) {
if (s.kind === "square") {
return s.size * s.size;
}
else if (s.kind === "rectangle") {
return s.width * s.height;
}
else if (s.kind === "circle") {
return Math.PI * s.radius * s.radius;
}
else {
//Type 'Square | Rectangle' is not assignable to type 'never'.
const _exhaustiveCheck: never = s;
}
}
//Function lacks ending return statement and return type does not include 'undefined'.
function area2(s: Shape): number {
switch (s.kind) {
case "square": return s.size * s.size;
case "rectangle": return s.width * s.height;
case "circle": return Math.PI * s.radius * s.radius;
default: const _exhaustiveCheck: never = s; //Type of s is 'never'
}
}
질문 (--strictNullChecks)에서 다음 코드 :이 개 기능 s
에서
- 이유는 무엇입니까 in expression
_exhaustiveCheck: never = s
다른 유형이 있습니까? 두 경우 모두s
이never
일 것으로 예상했습니다. - 왜
area2
함수가 반환 유형을 갖고 싶습니까number | undefined
? 그것은 나에게 정의되지 않은 것처럼 여기에서 일어날 수없는 것처럼 보인다. 내가 잘못?
https://github.com/basarat/typescript-book/blob/master/docs/types/discriminated-unions.md#strictnullchecks이 친절하고 성가신 질문을 알고 보니이 답변을 주셔서 감사합니다. 나는 아마 뭔가를 엉망으로 만들었고이 문제는's' 인'Square | 직사각형 '을 선택합니다. 죄송합니다. 다음 번에는 문제가 생기고 잠시 휴식을 취하고 질문을 게시 할 것입니다. 나는 또한 책의 당신의 버전을 읽을 것이고, 그것이 잘못된 버전인지 알지 못했다 :-) –