我正在遷移到較新版本的打字稿,但開始在型別保護中出現此錯誤。
在 else 分支中,它的顯示問題是 never 型別,而不是顯示問題是 Question 型別。當我在 typescript v3.9.5 中運行它時它作業正常,但在 v4.5.4 中它給出了這個錯誤。粘貼在我的代碼片段下方。vs代碼中還有一個錯誤的參考影像
export enum QuestionTypesEnum {
TYPE1 = 'type1',
TYPE2 = 'type2'
}
export type McqSingle = {
hash: string
type: QuestionTypesEnum
answer: string;
}
export type McqMultiple = {
hash: string
type: QuestionTypesEnum
answers: string[]
}
export type Question =
| McqSingle
| McqMultiple
type EmptyQuestion = { hash: string }
const isEmptyQuestion = (question: Question | EmptyQuestion): question is EmptyQuestion => {
return !('type' in question)
}
let question: Question | EmptyQuestion = { hash: 'saas', type: QuestionTypesEnum.TYPE1 }
if (isEmptyQuestion(question)) {
}
else {
question.type // <-- Typescript complains that "Property 'type' does not exist on type 'never'"
}
游樂場鏈接
錯誤是:
打字稿抱怨“'從不'型別上不存在屬性'型別'”
vs代碼中的TS錯誤
uj5u.com熱心網友回復:
問題在于它是(實體是有效實體)Question的超集。結果,您的型別謂詞根本不會縮小變數范圍;它在分支中的型別仍然是.EmptyQuestionQuestionEmptyQuestionquestionifQuestion | EmptyQuestion
如果您將型別謂詞反轉為檢查它,它會起作用Question,因為雖然Question是有效的EmptyQuestion,但EmptyQuestion不是有效的Question:
const isQuestion = (question: Question | EmptyQuestion): question is Question => {
return 'type' in question;
};
// ...
if (isQuestion(question)) {
question.type
// ^? ???? type is Question
} else {
question.hash
// ^? ???? type is EmptyQuestion
}
游樂場鏈接
uj5u.com熱心網友回復:
如果您想使用現有代碼。
question['type']
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/481412.html
標籤:javascript 打字稿 打字员
