如何区分TypeScript重载中的类型对象和数组?

时间:2018-07-06 15:51:29

标签: javascript typescript generics types overloading

这是我的代码:

public foo<T>(src: object, type: Type<T>): T;
public foo<T>(src: any[], type: Type<T>[]): T[];
public foo<T>(src: object | any[], type: Type<T> | Type<T>[]): T | T[] {...}

我想做的是保证以下约束的重载:

  • 一个对象(不是数组),一个Type>单个对象
  • 一个数组,一个Type数组>一个数组

问题在于类型对象也可以是数组,因此可以进行以下组合:

foo([...], MyType) > {}

有办法避免吗?还是可以向我推荐重写过载的方法?

1 个答案:

答案 0 :(得分:1)

问题是数组是一个对象,因此如果采用数组参数的重载未能匹配,Typescript将继续进行下一个采用对象的重载,并得出第一个参数与{兼容的结论。 {1}}。

如果第一个参数是对象重载上的数组,则可以使用条件类型在第二个参数中引入不兼容性。另外,如果您需要推断一个数组的更多类型,则需要指定更多类型参数(每种类型最多指定一个合理的类型)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.divya.niluv1"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'
    implementation 'com.android.support:design:28.0.0-alpha1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0-beta6'
    // implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}