microsoft / microsoft/TypeScript

Cannot describe recursive type aliases like JSON in terms of generic mapped types

Open
#57,034 1 comment 7 reactions 1 assignee View on GitHub

Nobody has claimed this yet.

In Discussion Suggestion
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

In the following examples, I've defined 4 different versions of a Json type, where they differ on their description of object types.

Playground link here.

In the first two, I've defined them in terms of mapped types with a concrete key of string, and an object type with a string index signature. TypeScript has no issues with either of those.

On the other hand, the last two are described with Record, or with a helper mapped type fed in a string key type.

// No errors ✅
namespace ObjectIsMappedTypeOnString {
    export type Json =
        | string
        | number
        | boolean
        | null
        | Json[]
        | { [K in string]: Json }
        ;
}

// No errors ✅
namespace ObjectIsIndexSignature {
    export type Json =
        | string
        | number
        | boolean
        | null
        | Json[]
        | { [key: string]: Json }
        ;
}

// Errors ❌
namespace ObjectIsRecord {
    export type Json =
        | string
        | number
        | boolean
        | null
        | Json[]
        | Record<string, Json>
        ;
}

// Error ❌
namespace ObjectIsGenericMappedType {
    type JsonProperties<K extends PropertyKey> = {
        [P in K]: Json
    };
    export type Json =
        | string
        | number
        | boolean
        | null
        | Json[]
        | JsonProperties<Json>
        ;
}

I would expect all of these to work.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.