Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

173
Visualizações
Type 'null' is not assignable to type 'T'

I have this generic method

class Foo { 
     public static bar<T>(x: T): T {
         ...
         if(x === null)
             return null; //<------- syntax error
         ...
     }
 }


... //somewhere
const x = Foo.bar<number | null>(1);

I'm getting the syntax error

TS2322: Type 'null' is not assignable to type 'T'.

I'm expecting this to compile because T could be null.

what is the proper way to solve this problem

over 4 years ago · Santiago Trujillo
5 Respostas
Responde à pergunta

0

You have to declare the return type as null or turn off strictNullChecks in your tsconfig

public static bar<T>(x: T): T | null

or you could type null as any e.g.

 return null as any;
over 4 years ago · Santiago Trujillo Relatório

0

I would propose here function overloads in order to remove null case for arguments being non-nullable. Consider:

class Foo { 
    public static bar<T>(x: T): T // overload
    public static bar(x: null): null // overload
    public static bar<T>(x: T) {
        if (x === null) {
            return null;
        } else
            return x;
     }
 }

const x = Foo.bar(1 as number); // x is number, never a null
const y = Foo.bar(null); // its null
const z = Foo.bar('s' as string | null); // its string | null

So the implementation has type T | null but thanks to overload for types which are never null we have return type of T so without the null possibility.

over 4 years ago · Santiago Trujillo Relatório

0

Since version 3.9.5, TypeScript enforces strictNullChecks on numbers and strings just to name a few. For example, the following code will throw an error during compilation:

let x: number = null;

To avoid this error you have two options:

  • Set strictNullChecks=false in tsconfig.json.
  • Declare your variable type as any:
    let x: any = null;
    
over 4 years ago · Santiago Trujillo Relatório

0

Instead of null assign undefined to the variables.

over 4 years ago · Santiago Trujillo Relatório

0

You can put

return null!;

It worked for me

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda