microsoft / microsoft/TypeScript

Generic type can't be assigned to the same DeepReadonly type

Open
#32,198 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: Mapped Types
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

Assigning generic type T to it's deep readonly DeepReadonly<T> cause error however shallow Readonly<T> works fine. Also I found that known types do work well with DeepReadonly .

TypeScript Version: 3.4.0-dev.201xxxxx

Search Terms:
DeepReadonly assign return generic nested readonly

Code

// Simple deep readonly
export type DRO<T> = { readonly [P in keyof T]: DR<T[P]> };
type DR<T> = T extends object ? DRO<T> : T;

// Sample type
interface TMP {
  a: number;
  b: {
    c: boolean;
  };
}

// Works fine
const a: TMP = { a: 10, b: { c: false } };
const b: DRO<TMP> = a;

// Doesn't work
class X<T> {
  constructor(private readonly t: T) {}

  foo(): DRO<T> {
    // Error here
    return this.t; 
  }

  bar(): Readonly<T> {
    // Works fine
    return this.t;
  }
}

Expected behavior:
Method foo shouldn't have error

Actual behavior:
Error: Type 'T' is not assignable to type 'DRO'.

Playground Link:
https://www.typescriptlang.org/play/#code/PTAEGUEsFsAcBsCmoAmjG1AJ0QQxQPYB28AngFCIAesBWALqPabMgCIBKA8gDwAqAPlABeUAG9seQiVKgA2gAVQkIqADWiUgQBmoPgF0AXKE79F+oQF8A3OWasTHfkNF9Q1eoiIoAzqAIARgBWiADGjAD8jryCoMZ8tuQgELhwSEwsiOQqnljauKHIfACySmLkoKC4xkQArtABiFi2lQHG5ZWVocYBBARIuEQtoDbkluRJYADqdGp+2ipZocQ+jNV6pSLiVcYAjAAMADSgbdvdoPnwPsiWI7bLRKsnxpwxpS5ViclsBIg+RAByRgAd1m5FC8FwPj8AA1nOIKqAHqssLVwnQABSwLCQABuuE8knwxDITHiAEpxONEdo+hjyS9uPCOp1kgBRLBYOigAAWTSynUk9FqWFU9B5kB8ADp6NZQIjqa1cFh6cYOFISaRmYjKskZlg5hdFjqhSKxRLpbKFWMgA

Related Issues:
Maybe: #12826 and #21919

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.

Research direction

Start with the TypeScript Playground reproduction and compare its behavior with the referenced TypeScript version or a current build. Investigate the generic assignment from T to DRO, alongside the working concrete and Readonly cases. Done means the reported generic foo method no longer produces the stated error without regressing the existing cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.