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

Add isFulfilled and isRejected for PromiseSettledResult[] #30

Closed
tychenjiajun opened this issue Jan 27, 2022 · 6 comments
Closed

Add isFulfilled and isRejected for PromiseSettledResult[] #30

tychenjiajun opened this issue Jan 27, 2022 · 6 comments

Comments

@tychenjiajun
Copy link
Contributor

No description provided.

@tychenjiajun tychenjiajun changed the title Add isFulFilled and isRejected for PromiseSettledResult[] Add isFulfilled and isRejected for PromiseSettledResult[] Jan 27, 2022
@sindresorhus
Copy link
Owner

I don't intent to modify built-in methods here. We could make a similar method to Promise.allSettled, but is it really worth the overhead of having to import a method just for this?

@sindresorhus
Copy link
Owner

We have such method already.

@tychenjiajun
Copy link
Contributor Author

We have such method already.

Do you mean objectHasOwn? It doesn't work well with Array.prototype.filter:

const has = Object.prototype.hasOwnProperty;

function objectHasOwn<ObjectType, Key extends PropertyKey>(
    object: ObjectType,
    key: Key,
): object is ObjectType & Record<Key, unknown> {
    // TODO: Use `Object.hasOwn()` when targeting Node.js 16.
    return has.call(object, key);
}
const results: PromiseSettledResult<string>[] = [{ status: 'fulfilled', value: 'foo' }, { status: 'rejected', reason: 'foo' }]

// typeof fulfilled is still PromiseSettledResult not PromiseFulfilledResult
const fulfilled = results.filter(r => objectHasOwn(r, 'value'));

function isFulfilled<T>(object: PromiseSettledResult<T>) {
    return objectHasOwn(object, 'value');
}

// typeof fulfilled2 is still PromiseSettledResult not PromiseFulfilledResult
const fulfilled2 = results.filter(isFulfilled);

The goal of hasOwn is adding type guard for Array.prototype.filter. It's not only a modify built-in method.

@jonahsnider
Copy link
Contributor

That's not really an issue with objectHasOwn though. You should just make isFulfilled a type guard.

@tychenjiajun
Copy link
Contributor Author

Thank you for your replies! @jonahsnider @sindresorhus I think https://github.com/robertmassaioli/ts-is-present is exactly what I want.

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