Typescript: null許容型ではない型は、オプションのdestructuring(ng2)ではうまく機能しません。

作成日 2016年05月19日  ·  1コメント  ·  ソース: microsoft/TypeScript

TypeScriptバージョン:

毎晩(1.9.0-dev.20160217)

コード

export interface QueryMetadataFactory {
    (selector: Type | string, {descendants, read}?: {
        descendants?: boolean;
        read?: any;
    }): ParameterDecorator;
    new (selector: Type | string, {descendants, read}?: {
        descendants?: boolean;
        read?: any;
    }): QueryMetadata;
}

予想される行動:
厳密なnullチェックを使用してこれをコンパイルする場合、これが機能するため、非構造化変数がオプションとしてマークされているため、これがコンパイルされることを期待します。

export interface QueryMetadataFactory {
    (selector: Type | string, whatever?: {
        descendants?: boolean;
        read?: any;
    }): ParameterDecorator;
    new (selector: Type | string, whatever?: {
        descendants?: boolean;
        read?: any;
    }): QueryMetadata;
}

実際の動作:
コンパイル時:

node_modules/@angular/core/src/metadata.d.ts(356,32): error TS2459: Type '{ descendants?: boolean | undefined; read?: any; } | undefined' has no property 'descendants' and no string index signature.
node_modules/@angular/core/src/metadata.d.ts(356,45): error TS2459: Type '{ descendants?: boolean | undefined; read?: any; } | undefined' has no property 'read' and no string index signature.
node_modules/@angular/core/src/metadata.d.ts(360,36): error TS2459: Type '{ descendants?: boolean | undefined; read?: any; } | undefined' has no property 'descendants' and no string index signature.
node_modules/@angular/core/src/metadata.d.ts(360,49): error TS2459: Type '{ descendants?: boolean | undefined; read?: any; } | undefined' has no property 'read' and no string index signatu
Bug

最も参考になるコメント

これは境界線です。 関数

function foo({ a, b }?: { a: number, b: number }) {
}

分解しようとしている引数がundefined可能性があるため、実際にはエラーです。 したがって、例にある正確な署名を実装することはできません。 ここで、宣言をに変更すると

function foo({ a, b }: { a: number, b: number } = { a: 0, b: 0 }) {
}

undefinedがデフォルト値に置き換えられるため、エラーではなくなりました。 それでも、呼び出し元の観点からは、パラメーターはオプションであり、宣言ファイルを生成する場合は、宣言を吐き出します。

declare function foo({ a, b }?: { a: number, b: number }): void;

これによりエラーが発生します。 そして、それはバグです。

余談ですが、実装されていないシグニチャのパラメータを破壊しないようにすることをお勧めします。 これらは実際には実装の詳細です。つまり、関数の実装が引数を分解するのか、プロパティアクセスを使用するだけなのかは、呼び出し元にはあまり関係ありません。 ただし、宣言ファイルの場合、発行する実際のパラメーター名がないため、(しぶしぶ)破壊パターンを発行するため、バグを修正する必要があります。

>すべてのコメント

これは境界線です。 関数

function foo({ a, b }?: { a: number, b: number }) {
}

分解しようとしている引数がundefined可能性があるため、実際にはエラーです。 したがって、例にある正確な署名を実装することはできません。 ここで、宣言をに変更すると

function foo({ a, b }: { a: number, b: number } = { a: 0, b: 0 }) {
}

undefinedがデフォルト値に置き換えられるため、エラーではなくなりました。 それでも、呼び出し元の観点からは、パラメーターはオプションであり、宣言ファイルを生成する場合は、宣言を吐き出します。

declare function foo({ a, b }?: { a: number, b: number }): void;

これによりエラーが発生します。 そして、それはバグです。

余談ですが、実装されていないシグニチャのパラメータを破壊しないようにすることをお勧めします。 これらは実際には実装の詳細です。つまり、関数の実装が引数を分解するのか、プロパティアクセスを使用するだけなのかは、呼び出し元にはあまり関係ありません。 ただし、宣言ファイルの場合、発行する実際のパラメーター名がないため、(しぶしぶ)破壊パターンを発行するため、バグを修正する必要があります。

このページは役に立ちましたか?
0 / 5 - 0 評価