Skip to content
New issue

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

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

Already on GitHub? # to your account

Except is broken when used with generic property #232

Closed
szmarczak opened this issue Jul 23, 2021 · 12 comments · Fixed by #263
Closed

Except is broken when used with generic property #232

szmarczak opened this issue Jul 23, 2021 · 12 comments · Fixed by #263

Comments

@szmarczak
Copy link
Contributor

szmarczak commented Jul 23, 2021

class Example {
    foo: number;
    bar: string;

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

    [key: string]: unknown;
}

type Except<ObjectType, KeysType extends keyof ObjectType> = Pick<ObjectType, Exclude<keyof ObjectType, KeysType>>;
const test: Except<Example, 'bar'> = new Example();

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

Playground link

@szmarczak szmarczak changed the title Except is broken Except is broken when used with generic property Jul 23, 2021
@szmarczak
Copy link
Contributor Author

I just noticed Omit is broken as well 🤦🏼

@sindresorhus
Copy link
Owner

This sounds like a TS bug/limitation. Maybe open an issue about Omit and see what they say?

@szmarczak
Copy link
Contributor Author

@szmarczak
Copy link
Contributor Author

szmarczak commented Jul 24, 2021

type IfPrimitiveString<C, T, F> = string extends C ? T : F;
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
Contributor Author

I just wanted to note that is Except breaks everything that uses it, including Merge.

@sindresorhus
Copy link
Owner

Can we make a better Except type here?

@szmarczak
Copy link
Contributor Author

We can, but under a different name. Some people want Except<Example, string> to remove all string keys and some will want to remove only generic string keys.

@szmarczak
Copy link
Contributor Author

I'll do a PR.

@sindresorhus
Copy link
Owner

What would you name such a type?

@szmarczak
Copy link
Contributor Author

Maybe ExceptStrict?

@nghiepdev
Copy link

The problem reappeared in 2.5.2.

@sindresorhus
Copy link
Owner

I don't see how that's possible. Nothing related to Except was touched in 2.5.2.

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants