Skip to content

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

@vshab

Description

@vshab

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptDomain: Mapped TypesThe issue relates to mapped types

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions