![](/img/trans.png)
[英]What is the type of object when I do a map in a pipe on an observable?
[英]How can I define the object type in a returned pipe(map(...)) statement?
我開始在 Angular + Ionic Framework 中開發應用程序。
我的問題是我不知道如何在返回的 object 上定義類型以便能夠檢索特定屬性。
我認為這是一個常見問題,但我無法使用谷歌找到正確的結果。
當我嘗試從設備存儲返回我的身份驗證令牌時,它看起來像
{
key:'authData',
value: token
}
我無法編譯,因為我的值屬性在返回的storedData字段中未知。
錯誤 TS2339:類型“未知”上不存在屬性“值”。
return from(Storage.get({ key: 'authData' })).pipe(map(storedData => {
if (!storedData || !storedData.value) {
return null;
}
const parsedData = JSON.parse(storedData.value)
}
所以我正在尋找某種類型來定義 storedData object 上的接口類型。親切的問候!
您必須在文件頂部聲明 model
interface StoredData {
key: string;
value: string;
}
然后在您的代碼中:
return from(Storage.get({ key: 'authData' })).pipe(map(storedData: StoredData => {
if (!storedData || !storedData.value) {
return null;
}
const parsedData = JSON.parse(storedData.value)
}
或者,您可以使用以下方法欺騙 linter:
return from(Storage.get({ key: 'authData' })).pipe(map(storedData => {
if (!storedData || !storedData['value']) {
return null;
}
const parsedData = JSON.parse(storedData['value'])
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.