首页 > 解决方案 > 访问块外的变量

问题描述

我是 TypeScript 的初学者(很明显,我来自 java 世界)。我目前正在尝试做一个这样的映射器:

public getApercuTypePrestationFromTypePrestationEX044(typePrestationEX044: TypePrestationEX044): ApercuTypePrestation {
        let apercuTypePrestation: ApercuTypePrestation;
        if (null != typePrestationEX044) {
            apercuTypePrestation = new ApercuTypePrestation();
            apercuTypePrestation.codeTypePrestation == typePrestationEX044.code;
            apercuTypePrestation.libelleTypePrestation == typePrestationEX044.libelle;
        }

        console.log("A = " + typePrestationEX044.code);
        console.log("B = " + apercuTypePrestation.libelleTypePrestation);

        return apercuTypePrestation;
    }

但这显然不起作用:在控制台中,我有: A = A8C B = undefined

我该如何解决?

标签: typescript

解决方案


您正在使用==而不是=. 我已经更改===,它现在应该可以工作了。

public getApercuTypePrestationFromTypePrestationEX044(typePrestationEX044: TypePrestationEX044): ApercuTypePrestation {
        let apercuTypePrestation: ApercuTypePrestation;
        if (null != typePrestationEX044) {
            apercuTypePrestation = new ApercuTypePrestation();
            apercuTypePrestation.codeTypePrestation = typePrestationEX044.code;
            apercuTypePrestation.libelleTypePrestation = typePrestationEX044.libelle;
        }

        console.log("A = " + typePrestationEX044.code);
        console.log("B = " + apercuTypePrestation.libelleTypePrestation);

        return apercuTypePrestation;
    }

在打字稿中, =====用于比较而不是分配,以便分配您必须使用的值=

更新

我还注意到您typePrestationEX044以错误的方式检查 null 。

改变这个:

if (null != typePrestationEX044) {
            apercuTypePrestation = new ApercuTypePrestation();
            apercuTypePrestation.codeTypePrestation = typePrestationEX044.code;
            apercuTypePrestation.libelleTypePrestation = typePrestationEX044.libelle;
        }

至此

if (typePrestationEX044) {
            apercuTypePrestation = new ApercuTypePrestation();
            apercuTypePrestation.codeTypePrestation = typePrestationEX044.code;
            apercuTypePrestation.libelleTypePrestation = typePrestationEX044.libelle;
        }

if条件将自动检查undefined,nullboolean


推荐阅读