[英]Tell TypeScript that a variable is of a certain type without assigning?
我想告訴TypeScript,在case塊中,變量是某種更具體的類型。
我知道我能做到
switch (message.type) {
case 'information':
let informationMessage = message as ServerInformation;
break;
}
但是沒有任何JavaScript分配可以做同樣的事情嗎? 我正在尋找類似的東西:
switch (message.type) {
case 'information':
message as ServerInformation;
break;
}
沒有像你預期的那樣直接做到這一點,但有一個解決方法
interface ServerInformation1 {
type: 'information1';
a: boolean;
}
interface ServerInformation2 {
type: 'information2';
b: boolean;
}
let message: ServerInformation1 | ServerInformation2;
switch (message.type) {
case 'information1':
const a1 = message.a; // this is ok
const b1 = message.b; // this will throw an error
break;
case 'information2':
const a2 = message.a; // this will throw an error
const b2 = message.b; // this is ok
break;
}
是的你可以。 第一種方式 - 使用受歧視的工會。
interface ServerInformation {
kind: "information";
text: string;
}
interface ErrorMessage {
kind: "error";
error: any;
}
....
switch (message.type) {
case 'information':
// message is ServerInformation
return message.text;
}
第二種方式 - 使用用戶定義的類型保護
function isServerInformation(message: ServerInformation | any): message is Fish {
return message.type === 'information';
}
...
if (isServerInformation(message)) {
// message is ServerInformation
return message.text;
}
在一天結束時,打字稿被轉換成js。
let informationMessage = message as ServerInformation;
被轉化為簡單的任務。
什么應該message as ServerInformation;
被編入? 此外,這不會檢查消息的類型,這是對此類型的消息播送消息。 如果您想要進行類型檢查,則需要:
let informationMessage: ServerInformation = message;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.