[英]How can I reuse a variable in typescript?
我想在不同的情況下使用我的可變children
:
var children = [];
if (folderPath == '/') {
var children = rootFolder;
} else {
var children = folder.childs;
}
但我收到錯誤消息:
變量“children”必須是“any[]”類型,但這里有“Folder[]”類型
這是什么意思?
一般來說,如果“為不同的情況使用變量”涉及將它們用於不同的類型,那么你做錯了。
假設rootFolder
是Folder
類型,而folder.childs
是Folder[]
,您的代碼看起來可能類似於
const children: Folder[] = (folderPath === '/' ? [rootFolder] : folder.childs);
事實上你應該能夠做到
const children = (folderPath === '/' ? [rootFolder] : folder.childs);
也讓推理來處理事情。
如果你想使用if
,那么
const children: Folder[];
if (folderPath === '/') {
children = [rootFolder];
} else {
children = folder.childs;
}
應該沒事; TypeScript 會注意到變量總是在if
之后肯定設置,即使它沒有初始值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.