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 IsUnion<T> #174

Closed
willium opened this issue Dec 20, 2020 · 5 comments
Closed

Add IsUnion<T> #174

willium opened this issue Dec 20, 2020 · 5 comments

Comments

@willium
Copy link

willium commented Dec 20, 2020

Found this super helpful in my project, we should add it :)

Upvote & Fund

  • We're using Polar.sh so you can upvote and help fund this issue.
  • The funding will be given to active contributors.
  • Thank you in advance for helping prioritize & fund our backlog.
Fund with Polar
@sindresorhus
Copy link
Owner

sindresorhus commented Dec 21, 2020

How do you use it? What problems does it solve?

@willium
Copy link
Author

willium commented Dec 30, 2020

export type Field<T extends SemanticType = SemanticType> = {
	readonly id: FieldId
	readonly type: T
	readonly name?: string
	readonly description?: string
	readonly isHidden?: boolean
}

export const isField = <T extends SemanticType = SemanticType>(
	val: unknown,
	type?: true extends IsUnion<T> ? T[] : T,
): val is Field<T> => {
	if (!isObject(val)) return false
	if (!isPlainObject(val)) return false
	const field = val as Field
	if (!field.id || typeof field.id !== "string") return false
	if (!field.type || typeof field.type !== "string") return false
	if (Array.isArray(type) && !type.includes(field.type)) return false
	if (type && field.type !== type) return false
	if (field.name && typeof field.name !== "string") return false
	if (field.description && typeof field.description !== "string") return false
	if (field.isHidden !== undefined && typeof field.isHidden !== "boolean") {
		return false
	}
	return true
}

@papb
Copy link
Contributor

papb commented Jan 3, 2021

@willium Can you explain?

@willium
Copy link
Author

willium commented Jan 3, 2021

I'm restricting the allowed type of Field by the types of value(s) passed in as a second parameter

@sindresorhus
Copy link
Owner

Duplicate of #236

@sindresorhus sindresorhus marked this as a duplicate of #236 Aug 5, 2021
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