AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 78874222
Accepted
Eliya Cohen
Eliya Cohen
Asked: 2024-08-15 16:21:12 +0800 CST2024-08-15 16:21:12 +0800 CST 2024-08-15 16:21:12 +0800 CST

TypeScript não detecta a sobrecarga de função correta

  • 772

Dada a seguinte implementação de função:

function fmap<T, U>(value: T, f: (x: T) => U): U;
function fmap<T, U>(value: T | undefined, f: (x: T) => U): U | undefined;
function fmap<T, U>(value: T | null, f: (x: T) => U): U | null;
function fmap<T, U>(value: T | null | undefined, f: (x: T) => U): U | null | undefined {
    return value === undefined ? undefined : value === null ? null : f(value);
}

Eu obtenho os tipos corretos nos seguintes casos:

const test1 = (v: string) => fmap(v, x => x); // ✅ expected: string
const test2 = (v: string | null) => fmap(v, x => x); // ✅ expected: string | null
const test3 = (v: string | undefined) => fmap(v, x => x); // ✅ expected: string | undefined
const test4 = (v: string | null | undefined) => fmap(v, x => x); // ✅ expected: string | null | undefined
const test5 = (v: string) => fmap(v, x => 1); // ✅ expected: number

Mas não nestes casos:

// ❌ expected: number | null (actual: number)
const test6 = (v: string | null) => fmap(v, x => 1);

// ❌ expected: number | undefined (actual: number)
const test7 = (v: string | undefined) => fmap(v, x => 1);

// ❌ expected: number | null | undefined (actual: number)
const test8 = (v: string | null | undefined) => fmap(v, x => 1);

Veja Parque Infantil

typescript
  • 2 2 respostas
  • 51 Views

2 respostas

  • Voted
  1. Best Answer
    HairyHandKerchief23
    2024-08-15T18:37:58+08:002024-08-15T18:37:58+08:00

    Você precisará extrair tipos anuláveis ​​do Ttipo genérico

    type ExtractedNullable<T> = Extract<T, null | undefined>
    
    function fmap<T, U>(value: T, f: (x: T) => U): U | ExtractedNullable<T> {
        return value === undefined ? undefined as ExtractedNullable<T> : value === null ? null as ExtractedNullable<T> : f(value);
    }
    
    const test1 = (v: string) => fmap(v, x => x); // ✅ expected: string
    const test2 = (v: string | null) => fmap(v, x => x); // ✅ expected: string | null
    const test3 = (v: string | undefined) => fmap(v, x => x); // ✅ expected: string | undefined
    const test4 = (v: string | null | undefined) => fmap(v, x => x); // ✅ expected: string | null | undefined
    const test5 = (v: string) => fmap(v, x => 1); // ✅ expected: number
    
    const test6 = (v: string | null) => fmap(v, x => 1); // number | null
    
    const test7 = (v: string | undefined) => fmap(v, x => 1); // number | undefined
    
    const test8 = (v: string | null | undefined) => fmap(v, x => 1); // number | null | undefined 
    
    • 2
  2. Jolly Sim
    2024-08-15T18:42:14+08:002024-08-15T18:42:14+08:00
    const test1 = (v: string) => fmap(v, x => x); // ✅ expected: string
    const test2 = (v: string | null) => fmap(v, x => x); // ✅ expected: string | null
    const test3 = (v: string | undefined) => fmap(v, x => x); // ✅ expected: string | undefined
    const test4 = (v: string | null | undefined) => fmap(v, x => x); // ✅ expected: string | null | undefined
    const test5 = (v: string) => fmap(v, x => 1); // ✅ expected: number
    
    // Should now correctly infer
    const test6 = (v: string | null) => fmap(v, x => 1); // ✅ expected: number | null
    const test7 = (v: string | undefined) => fmap(v, x => 1); // ✅ expected: number | undefined
    const test8 = (v: string | null | undefined) => fmap(v, x => 1); // ✅ expected: number | null | undefined
    
    • 0

relate perguntas

  • Por que usamos colchetes `[]` em condicionais?

  • Problema do Nestjs em relação aos módulos

  • Como obter metadados datilografados de um arquivo?

  • Como converter array em tipo const de retorno de objeto assim?

  • "Nenhuma sobrecarga corresponde" minha chamada Object.assign(); como posso corrigir isso?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle?

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Quando devo usar um std::inplace_vector em vez de um std::vector?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Martin Hope
    Aleksandr Dubinsky Por que a correspondência de padrões com o switch no InetAddress falha com 'não cobre todos os valores de entrada possíveis'? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge Por que esse código Java simples e pequeno roda 30x mais rápido em todas as JVMs Graal, mas não em nenhuma JVM Oracle? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer Quando devo usar um std::inplace_vector em vez de um std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB Por que o GCC gera código que executa condicionalmente uma implementação SIMD? 2024-02-17 06:17:14 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve