it-source

유형 스크립트에서 null 가능한 값을 반환하려면 어떻게 해야 합니까?

criticalcode 2023. 6. 25. 20:09
반응형

유형 스크립트에서 null 가능한 값을 반환하려면 어떻게 해야 합니까?

NPM 모듈에서 나는 타자 스크립트를 사용합니다.

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

공용 메서드를 사용하여 개인 null 가능 매개 변수를 반환하고 싶습니다.아래의 샘플을 참고하시기 바랍니다.내가 보는 오류는

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

생성자에서 정의되지 않은 항목을 할당하면 오류가 발생합니다.

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

타자기로 어떻게 해야 하나요, 저는 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;
    }
}

정의할 수 있습니다.

private string1: string | undefined;

표시되는 오류 메시지Type 'string | undefined' is not assignable to type 'string'당신이 할당했기 때문이 아닙니다.this.string = undefined생성자에서, 그것은 당신이 정의했기 때문입니다.getString1()돌아오는 길에string그리고 당신은 그것을 확인하지 않았습니다.this.string1사실은 끈이었습니다.

변경할 수 있습니다.getString1()그래서 그것은 사실 항상 문자열을 반환합니다, 그렇지 않으면 당신은 그것을 반환할 수 있습니다.string|undefined또는 훨씬 더 간단하게 초기화할 수 있습니다.string1정의되지 않은 상태로 유지할 수 있습니다.

이렇게 하면 효과가 있습니다.

export class HowToDoThis {
    private string1?: string;

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

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

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

하지만 이것은 단지 전화하기 때문에 더 좋을 것입니다.add2String1('foo')당신에게 줄을 주지 않을 것입니다.'undefinedfoo':

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

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

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

그리고 이것은 무엇보다도 가장 좋습니다(타입 스크립트에서 getter 함수를 사용하지 마십시오. 항상 생성할 수 있습니다.get나중에 속성에 액세스할 때 작업을 수행해야 하는 경우):

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

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

뭘 하고 싶은지 모르겠어요?정의되지 않은 항목을 원하는 이유는 무엇입니까?저는 당신이 콘텐츠를 "정의되지 않음"과 연결하고 싶어하지 않는다고 생각합니다.

따라서 사용:

private string1 = "";

또는

private string1: string;
public constructor() {
    this.string1 = "";
}

언급URL : https://stackoverflow.com/questions/49874116/how-could-i-return-a-nullable-value-in-typescript

반응형