reactjs 类型'承诺〈(字符串[]|未定义)[]>"缺少类型“Etablissement[]”中的以下属性:长度、弹出、推送、连续以及29种以上

ruyhziif  于 2023-03-17  发布在  React
关注(0)|答案(4)|浏览(203)

。你好,在下面代码的帮助下,我尝试通过异步查询检索“Etablissement”表。最后一行带有红色下划线,并显示以下消息:
Type 'Promise<(string[] | undefined)[]>' is missing the following properties from type 'Establishment[]': length, pop, push, concat, and 29 more.
如果任何人有一个想法,任何解决方案的建议将不胜感激。提前感谢您的帮助。
下面是一个代码片段:

interface GetApplicationHook {
    getApplication: (id?: string) => Promise<ApplicationToSave>
    defaultApplication: ApplicationToSave
    getOneEtablissement: (uai?: string) => Promise<Etablissement>
    toEtablissementsList: (ouList: string[]) => Etablissement[]
}
[...]
const getOneEtablissement = (uai?: string): Promise<Etablissement> => {
        if (uai) {
            return loadOneEtablissement(uai)
                .then((etab: Etablissement) => {
                    return {
                        nom: etab.nom,
                        uai: etab.uai,
                        ou: etab.ou,
                        description: etab.description,
                    }
                })
                .catch(() => Promise.reject("Erreur à la récupération de l'établissement=" + uai))
        }
        return Promise.resolve(defaultEtablissement)
    }

    const fromOuToUai = (ou: string): string => {
        try {
            return ou.split(',')[0].split('=')[1]
        } catch (error) {
            return ou
        }
    }

    const toEtablissementsList = (ouList: string[]): Etablissement[] => {
        const etabList = Promise.all(
            ouList.map(ou => {
                try {
                    const uai = fromOuToUai(ou)
                    getOneEtablissement(uai)
                        .then((data: Etablissement) => data)
                        .catch(() => Promise.reject())
                } catch (error) {
                    return ouList
                }
            })
        )
        return etabList
    }

[...]

我一直在寻找关于Promises如何工作以及如何从中提取感兴趣的数据的信息。如果我理解正确的话,这应该通过.then()方法沿着.catch()方法来完成...但这似乎还不够。问题显然是关于键入,但我不明白问题出在哪里。

eufgjt7s

eufgjt7s1#

代码最后一行的问题是etabList是解析为Etablissement[]数组而不是Etablissement对象数组的Promise。这是因为Promise.all()返回解析为输入Promise的解析值数组的Promise。
您需要修改toEtablissementsList()函数,等待Promise.all()调用解析,然后返回生成的Etablissement[]数组。您还可以通过删除不必要的try-catch块来简化代码。
大概是这样的

const toEtablissementsList = async (ouList: string[]): Promise<Etablissement[]> => {
  const etabListPromises = ouList.map(ou => {
    const uai = fromOuToUai(ou);
    return getOneEtablissement(uai);
  });

  const etabList = await Promise.all(etabListPromises);
  return etabList;
}

你可以创建一个Promise<Etablissement>对象的数组,方法是Map到ouList数组上,并为每个uai调用getOneEtablissement()。然后使用Promise.all()等待所有承诺解析,并返回结果Etablissement[]数组。
还将toEtablissementsList()的返回类型更改为Promise<Etablissement[]>,因为该函数是异步的并且返回Promise

***针对请求编辑:***要从Promise〈Etablissement[]〉中提取Etablissement[],您需要使用await关键字或then()方法等待解析该Promise。

function getEtablissementsList() {
  const ouList = ["ou1", "ou2", "ou3"];
  const etabListPromise = toEtablissementsList(ouList);
  etabListPromise.then(etabList => {
    console.log(etabList); // do something with the Etablissement[] array
  });
}

getEtablissementsList();
0pizxfdo

0pizxfdo2#

代码的问题在于toEtablissementsList函数返回的是Promise,而不是Etablissement对象数组。
试试这个:

const toEtablissementsList = (ouList: string[]): Promise<Etablissement[]> => {
  return Promise.all(
    ouList.map((ou) => {
      try {
        const uai = fromOuToUai(ou);
        return getOneEtablissement(uai);
      } catch (error) {
        return Promise.reject(error);
      }
    })
  ).then((etabList) => etabList.filter((etab) => !!etab));
};
t9aqgxwy

t9aqgxwy3#

以下是完整的组件代码,如果有帮助的话(底部的属性listOrganisations需要是Etablissement[]):

import ApplicationRole from 'domain/ApplicationRole'
import ApplicationProfile from 'domain/ApplicationProfile'
import ApplicationToSave from 'domain/ApplicationToSave'
import useAppsToutaticeService from 'service/AppsToutaticeService'
import TimeUtils from './TimeUtils'
import Etablissement from 'domain/Etablissement'
import useEtablissementService from 'service/EtablissementService'

interface GetApplicationHook {
    getApplication: (id?: string) => Promise<ApplicationToSave>
    defaultApplication: ApplicationToSave
    getOneEtablissement: (uai?: string) => Promise<Etablissement>
    toEtablissementsList: (ouList: string[]) => Etablissement[]
}

const GetApplication = (): GetApplicationHook => {
    const { loadApp } = useAppsService()
    const { loadOneEtablissement } = useEtablissementService()

    const defaultApplication = {
        applicationId: '',
        nom: '',
        description: '',
        categorie: ' ',
        dateFermeture: '',
        dateOuverture: '',
        icone: '',
        statut: '',
        urlConnexion: '',
        urlDeconnexion: '',
        dnmaTypeService: '',
        dnmaCategorie: ' ',
        dnmaUai: '',
        dnmaOutil: ' ',
        listeManagers: [],
        listeExplicitManagers: [],
        listeExplicitMembers: [],
        listeOrganisations: [],
        listeProfils: [],
        listeRoles: [],
    }

    const defaultEtablissement = {
        nom: '',
        uai: '',
        ou: '',
        description: '',
    }

    const getFirstElementOrDefault = (elements?: string[], defaultValue = '') => {
        if (elements && elements.length > 0) return elements[0]
        return defaultValue
    }

    const toApplicationProfile = (profile: string): ApplicationProfile => {
        return {
            dn: profile,
            cn: profile.split(',')[0].split('=')[1],
        }
    }

    const toApplicationProfileList = (profileList: string[]): ApplicationProfile[] => {
        if (profileList && profileList.length > 0) {
            return profileList.map(profile => toApplicationProfile(profile))
        }
        return []
    }

    const toApplicationRole = (appRole: string): ApplicationRole => {
        return {
            cn: appRole.split(',')[0].split('=')[1],
            dn: appRole,
            nom: '',
            description: '',
            listeProfils: [],
            listeProprietaires: [],
            listeManagers: [],
            listeExplicitManagers: [],
            listeTags: [],
            listeMemberUrl: [],
        }
    }

    const toApplicationRoleList = (appRolesList: string[]): ApplicationRole[] => {
        if (appRolesList && appRolesList.length > 0) {
            return appRolesList.map(appRole => toApplicationRole(appRole))
        }
        return []
    }

    const { isoToDate } = TimeUtils()

    const getOneEtablissement = (uai?: string): Promise<Etablissement> => {
        if (uai) {
            return loadOneEtablissement(uai)
                .then((etab: Etablissement) => {
                    return {
                        nom: etab.nom,
                        uai: etab.uai,
                        ou: etab.ou,
                        description: etab.description,
                    }
                })
                .catch(() => Promise.reject("Erreur à la récupération de l'établissement=" + uai))
        }
        return Promise.resolve(defaultEtablissement)
    }

    const fromOuToUai = (ou: string): string => {
        try {
            return ou.split(',')[0].split('=')[1]
        } catch (error) {
            return ou
        }
    }

    const toEtablissementsList = (ouList: string[]): Etablissement[] => {
        const etabList = Promise.all(
            ouList.map(ou => {
                try {
                    const uai = fromOuToUai(ou)
                    getOneEtablissement(uai)
                        .then((data: Etablissement) => data)
                        .catch(() => Promise.reject())
                } catch (error) {
                    return ouList
                }
            })
        )
        return etabList
    }

    const getApplication = (id?: string): Promise<ApplicationToSave> => {
        if (id) {
            return loadApp(id)
                .then(app => {
                    return {
                        applicationId: app.applicationId,
                        description: app.description,
                        nom: app.nom,
                        categorie: getFirstElementOrDefault(app.listeCategories, ' ').toLocaleLowerCase(),
                        dateFermeture: isoToDate(app.endTime),
                        dateOuverture: isoToDate(app.startTime),
                        icone: app.icone ?? '',
                        statut: app.statut ?? 'TITI',
                        urlConnexion: app.url ?? '',
                        urlDeconnexion: getFirstElementOrDefault(app.listeUrlLogout),
                        dnmaTypeService: app.dnmaTypeService ?? 'TOTO',
                        dnmaCategorie: app.dnmaCatego ?? ' ',
                        dnmaUai: app.dnmaRne ?? 'TUTU',
                        dnmaOutil: app.dnmaOutil ?? ' ',
                        listeManagers: [],
                        listeExplicitMembers: [],
                        listeExplicitManagers: [],
                        listeOrganisations: toEtablissementsList(app.listeOrganisations),
                        listeProfils: toApplicationProfileList(app.listeProfils),
                        listeRoles: toApplicationRoleList(app.listeRoles),
                    }
                })
                .catch(() => Promise.reject("Erreur à la récupération de l'application=" + id))
        }
        return Promise.resolve(defaultApplication)
    }
    return { getApplication, defaultApplication, getOneEtablissement, toEtablissementsList }
}

export default GetApplication
jc3wubiy

jc3wubiy4#

嗨,谢谢你的回答,
我最终使用了本吉建议的函数,之后我在我的代码中做了一些其他的修改。如果它能帮助任何人,这里是最终的结果。
祝你愉快!

import ApplicationRole from 'domain/ApplicationRole'
    import ApplicationProfile from 'domain/ApplicationProfile'
    import ApplicationToSave from 'domain/ApplicationToSave'
    import useAppsToutaticeService from 'service/AppsToutaticeService'
    import TimeUtils from './TimeUtils'
    import Etablissement from 'domain/Etablissement'
    import useEtablissementService from 'service/EtablissementService'
    import ApplicationToutatice from 'domain/ApplicationToutatice'
    
    interface GetApplicationHook {
        getApplication: (id?: string) => Promise<ApplicationToSave>
        defaultApplication: ApplicationToSave
    }
    
    const GetApplication = (): GetApplicationHook => {
        const { loadApp } = useAppsToutaticeService()
        const { loadOneEtablissement } = useEtablissementService()
    
        const defaultApplication = {
            applicationId: '',
            nom: '',
            description: '',
            categorie: ' ',
            dateFermeture: '',
            dateOuverture: '',
            icone: '',
            statut: '',
            urlConnexion: '',
            urlDeconnexion: '',
            dnmaTypeService: '',
            dnmaCategorie: ' ',
            dnmaUai: '',
            dnmaOutil: ' ',
            listeManagers: [],
            listeExplicitManagers: [],
            listeExplicitMembers: [],
            listeOrganisations: [],
            listeProfils: [],
            listeRoles: [],
        }
    
        const getFirstElementOrDefault = (elements?: string[], defaultValue = '') => {
            if (elements && elements.length > 0) return elements[0]
            return defaultValue
        }
    
        const toApplicationProfile = (profile: string): ApplicationProfile => {
            return {
                dn: profile,
                cn: profile.split(',')[0].split('=')[1],
            }
        }
    
        const toApplicationProfileList = (profileList: string[]): ApplicationProfile[] => {
            if (profileList && profileList.length > 0) {
                return profileList.map(profile => toApplicationProfile(profile))
            }
            return []
        }
    
        const toApplicationRole = (appRole: string): ApplicationRole => {
            return {
                cn: appRole.split(',')[0].split('=')[1],
                dn: appRole,
                nom: '',
                description: '',
                listeProfils: [],
                listeProprietaires: [],
                listeManagers: [],
                listeExplicitManagers: [],
                listeTags: [],
                listeMemberUrl: [],
            }
        }
    
        const toApplicationRoleList = (appRolesList: string[]): ApplicationRole[] => {
            if (appRolesList && appRolesList.length > 0) {
                return appRolesList.map(appRole => toApplicationRole(appRole))
            }
            return []
        }
    
        const { isoToDate } = TimeUtils()
    
        const defaultEtablissement = {
            nom: '',
            uai: '',
            ou: '',
            description: '',
        }
    
        const getOneEtablissement = (uai?: string): Promise<Etablissement> => {
            if (uai) {
                return loadOneEtablissement(uai)
                    .then((etab: Etablissement) => {
                        return {
                            nom: etab.nom,
                            uai: etab.uai,
                            ou: etab.ou,
                            description: etab.description,
                        }
                    })
                    .catch(() => Promise.reject("Erreur à la récupération de l'établissement=" + uai))
            }
            return Promise.resolve(defaultEtablissement)
        }
    
        const fromOuToUai = (ou: string): string => {
            try {
                return ou.split(',')[0].split('=')[1]
            } catch (error) {
                return ou
            }
        }
    
        const toEtablissementsList = async (ouList: string[]): Promise<Etablissement[]> => {
            const etabListPromises = ouList.map(ou => {
                const uai = fromOuToUai(ou)
                return getOneEtablissement(uai)
            })
    
            const etabList = await Promise.all(etabListPromises)
            return etabList
        }
    
        const toApplicationToSave = (app: ApplicationToutatice, etabListAsOu: string[]): Promise<ApplicationToSave> => {
            return toEtablissementsList(etabListAsOu)
                .then(etabList => {
                    return {
                        applicationId: app.applicationId,
                        description: app.description,
                        nom: app.nom,
                        categorie: getFirstElementOrDefault(app.listeCategories, ' ').toLocaleLowerCase(),
                        dateFermeture: isoToDate(app.endTime),
                        dateOuverture: isoToDate(app.startTime),
                        icone: app.icone ?? '',
                        statut: app.statut ?? 'TOTO',
                        urlConnexion: app.url ?? '',
                        urlDeconnexion: getFirstElementOrDefault(app.listeUrlLogout),
                        dnmaTypeService: app.dnmaTypeService ?? 'TITI',
                        dnmaCategorie: app.dnmaCatego ?? ' ',
                        dnmaUai: app.dnmaRne ?? 'TUTU',
                        dnmaOutil: app.dnmaOutil ?? ' ',
                        listeManagers: [],
                        listeExplicitMembers: [],
                        listeExplicitManagers: [],
                        listeOrganisations: etabList,
                        listeProfils: toApplicationProfileList(app.listeProfils),
                        listeRoles: toApplicationRoleList(app.listeRoles),
                    }
                })
                .catch(() => Promise.reject())
        }
    
        const getApplication = (id?: string): Promise<ApplicationToSave> => {
            if (id) {
                return loadApp(id)
                    .then(app => {
                        return toApplicationToSave(app, app.listeOrganisations)
                    })
                    .catch(() => Promise.reject("Erreur à la récupération de l'application=" + id))
            }
            return Promise.resolve(defaultApplication)
        }
    
        return { getApplication, defaultApplication }
    }
    
    export default GetApplication```

相关问题