web-dev-qa-db-fra.com

Comment pourrais-je retourner une valeur nullable en tapuscrit

dans un module NPM j'utilise TypeScript

  "devDependencies": {
    "@types/node": "^8.0.0",
    "TypeScript": "^2.8.1"
  }

et je veux retourner un paramètre nullable privé en utilisant une méthode publique. Veuillez vous référer à l'exemple ci-dessous. L'erreur que je vois est

Property 'string1' has no initializer and is not definitely assigned in the constructor.

Si j'attribue un indéfini dans le constructeur, j'ai l'erreur

[ts]
Type 'string | undefined' is not assignable to type 'string'.
  Type 'undefined' is not assignable to type 'string'

Comment dois-je faire cela en TypeScript, je suis du côté c # :)

export class HowToDoThis {

    private string1?: string;

    public constructor() {

        //this.string1 = undefined;
    }

    public add2String1(content: string) {

        this.string1 += content;
    }

    public getString1(): string {

        return this.string1;
    }
}
6
jstolz

Vous pouvez définir

private string1: string | undefined;
9
tru7

Le message d'erreur que vous obtenez Type 'string | undefined' is not assignable to type 'string' N'est pas parce que vous avez affecté this.string = undefined Dans le constructeur, c'est parce que vous avez défini getString1() comme renvoyant string et vous n'a pas vérifié que this.string1 était bien une chaîne.

Vous pouvez soit changer getString1() pour qu'il retourne en fait toujours une chaîne, soit le faire retourner string|undefined, Ou bien plus simple vous pouvez simplement initialiser string1 En un vide chaîne et ne l'ont jamais indéfinie.

Donc ça marche:

export class HowToDoThis {
    private string1?: string;

    public constructor() {
        this.string1 = undefined;
    }

    public add2String1(content: string) {
        this.string1 += content;
    }

    public getString1(): string {
        return this.string1 || "";
    }
}

Mais ce serait mieux si ce n'est que parce que l'appel de add2String1('foo') ne vous donnera pas la chaîne 'undefinedfoo':

export class HowToDoThis {
    private string1: string = "";

    public add2String1(content: string) {
        this.string1 += content;
    }

    public getString1(): string {
        return this.string1;
    }
}

Et c'est le meilleur de tous (n'utilisez pas les fonctions getter dans TypeScript, vous pouvez toujours créer une propriété get plus tard si vous devez faire quelque chose quand une propriété est accessible):

export class HowToDoThis {
    public string1: string = "";

    public add2String1(content: string) {
        this.string1 += content;
    }
}
1
Duncan

Pas sûr de ce que vous voulez faire? Pourquoi voulez-vous qu'il ne soit pas défini? Je ne pense pas que vous souhaitiez concaténer du contenu avec "non défini".

Alors utilisez:

private string1 = "";

ou

private string1: string;
public constructor() {
    this.string1 = "";
}
0
Mattias Almén