Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeScript: DeepPartial not working for union of string and string literals #174

Open
fluffy-heinzelman opened this issue Oct 29, 2021 · 0 comments

Comments

@fluffy-heinzelman
Copy link

fluffy-heinzelman commented Oct 29, 2021

Description

Consider the following unions, where union B is designed to provide intellisense code completion (in contrast to A, which is narrowed down to only string by the TS compiler).

If DeepPartial is applied on unions like B we get an TS error when we try to assign an arbitrary string value.

type A = 'foo' | 'bar' | string;
type B = 'foo' | 'bar' | (string & {});

type Key = 'x' | 'y' | 'z';

type ADict = DeepPartial<Record<Key, A>>;
type BDict = DeepPartial<Record<Key, B>>;

// - no code completion for values (as expected)
// - no error (as expected)
const a: ADict = {
    x: 'foo',
    y: 'barrel'
};

// - code completion for values (as expected)
// - TS error for any other string value than `foo` and `bar` (NOT expected)
const b: BDict = {
    x: 'foo',
    y: 'barrel' // TS error
};

Steps to Reproduce

Have a look at this Codesandbox:
https://codesandbox.io/s/issue-demo-utility-types-deeppartial-5zwnw?file=/src/index.ts

Expected behavior

DeepPartial not breaking unions of string and string literals.

Suggested solution(s)

DeepPartial conditional expressions could check for Primitive.

type DeepPartial<T> = 
    T extends Primitive ? Partial<T> : // FIX
    T extends Function ? T : 
    T extends Array<infer U>? DeepPartialArray<U> : 
    T extends object ? DeepPartialObject<T> : 
    T | undefined;

interface DeepPartialArray<T> extends Array<DeepPartial<T>> {}
type DeepPartialObject<T> = {
    [P in keyof T]?: DeepPartial<T[P]>;
};

Project Dependencies

  • Utility-Types Version: 3.10.0
  • TypeScript Version: 4.1.2
  • tsconfig.json:
{
  "compilerOptions": {
    "target": "es5",
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "sourceMap": true,
    "moduleResolution": "node",
    "allowJs": true,
    "noEmit": true,
    "strict": true,
    "esModuleInterop": true,
    "isolatedModules": false,
    "allowSyntheticDefaultImports": true
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant