简体   繁体   English

TypeScript:通用函数返回null

[英]TypeScript: Generic function return null

I am having the next function in typescript: 我在打字稿中有下一个功能:

In c# you have something like default(T) but in typescript I dont know. 在C#中,您有类似于default(T)的内容,但是在打字稿中,我不知道。

public Base {
...
}


public Get<T extends Base>(cultura: string): T[] 
{

    let res = null;

    try
    {

    }
    catch (ex)
    {
        throw ex;
    }

    return res;
}

I want to return a null but I get an error. 我想返回一个空值,但出现错误。 If I assign it in a variable the null and return the variable happens the same error. 如果我在变量中将其赋值为null并返回该变量,则会发生相同的错误。

Message is: The 'null' type can not be assigned to the type T[]. 消息是:'null'类型不能分配给类型T []。

The error is: 错误是:

在此处输入图片说明

How can I do it in TypeScript? 如何在TypeScript中做到这一点?

You have strict null checks on. 您必须严格执行null检查。 This means you cannot assign null to a variable (or return value) unless you've said that is a possibility. 这意味着除非有可能,否则不能将null赋给变量(或返回值)。 So either turn strict null checks off ( strictNullChecks: false in tsconfig.json ) or change the return type to T[] | null 因此,无论转严格null检查关( strictNullChecks: falsetsconfig.json )或返回类型更改为T[] | null T[] | null . T[] | null Or, better yet, return an empty array and not null. 或者,更好的是,返回一个空数组而不是null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM