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

Omit returns an invalid type when the target has a generic key #45177

Closed
szmarczak opened this issue Jul 24, 2021 · 9 comments
Closed

Omit returns an invalid type when the target has a generic key #45177

szmarczak opened this issue Jul 24, 2021 · 9 comments

Comments

@szmarczak
Copy link

szmarczak commented Jul 24, 2021

Bug Report

🔎 Search Terms

omit generic

🕗 Version & Regression Information

⏯ Playground Link

Playground link with relevant code

💻 Code

class Example {
    foo: number;
    bar: string;
	baz: string;

    constructor() {
        this.foo = 1;
        this.bar = '';
		this.baz = '';
    }

    [key: string]: unknown;
}

const test: Omit<Example, 'bar' | 'baz'> = new Example();

// `foo` is now `unknown`
console.log(test.foo + 5);

🙁 Actual behavior

test.foo is unknown

🙂 Expected behavior

test.foo should be number

@szmarczak

This comment has been minimized.

@jcalz
Copy link
Contributor

jcalz commented Jul 24, 2021

Duplicate of #43139 and others

@szmarczak
Copy link
Author

szmarczak commented Jul 24, 2021

This is extremely counterintuitive.

@szmarczak szmarczak reopened this Jul 24, 2021
@MartinJohns
Copy link
Contributor

It's due to the design of the language, and there are workaround available.

@szmarczak
Copy link
Author

I've updated the example. OmitIndex doesn't support union types as keys to remove.

@szmarczak
Copy link
Author

szmarczak commented Jul 24, 2021

there are workaround available.

I'm sure there are, but I don't want to write long lines like this

OmitIndex<OmitIndex<OmitIndex<Example, 'foo'>, 'bar'>, 'baz'>

@MartinJohns
Copy link
Contributor

I've updated the example. OmitIndex doesn't support union types as keys to remove.

There is no mention of a OmitIndex in your example.

@szmarczak
Copy link
Author

szmarczak commented Jul 24, 2021

See #41966

type EqualsTest<T> = <A>() => A extends T ? 1 : 0;
type Equals<A1, A2> = EqualsTest<A2> extends EqualsTest<A1> ? 1 : 0;

type Filter<K, I> = Equals<K, I> extends 1 ? never : K;

type OmitIndex<T, I extends string | number> = {
  [K in keyof T as Filter<K, I>]: T[K];
};

@szmarczak
Copy link
Author

Figured it out. I just need to fix the Filter like this:

type Filter<K, I> = Equals<K, I> extends 1 ? never : IfPrimitiveString<I, K, (K extends I ? never : K)>;

// or (which I prefer)
type Filter<K, I> = IfPrimitiveString<I, Equals<K, I> extends 1 ? never : K, K extends I ? never : K>;

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

3 participants