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 "has_property" and "has_value" type guards for objects #189

Open
raythurnvoid opened this issue Jan 5, 2024 · 1 comment · May be fixed by #191
Open

add "has_property" and "has_value" type guards for objects #189

raythurnvoid opened this issue Jan 5, 2024 · 1 comment · May be fixed by #191

Comments

@raythurnvoid
Copy link

Is your feature request related to a real problem or use-case?

Type guards for objects are done using the in operator. However it doesn't provide autocompletion and doesn't show an error if the tested property is not part of the object.

interface A {
	a?: number;
}

interface B {
	b: number;
}

const obj = { a: 1 } as A | B;

if ("invalid" in obj) {
	console.log(obj.invalid); // invalid is typed as "unknown"
}

Describe a solution including usage in code example

I propose to add two functions, I provide the implementation I'm using in personal projects.

type KeysOf<T> = T extends T ? keyof T : never;
type ExtractByKey<T, K extends KeysOf<T>> = Extract<T, { [P in K]?: any }>;
export function hasProperty<T extends object, K extends KeysOf<T>>(
	obj: T,
	key: K,
): obj is ExtractByKey<T, K> {
	return key in obj;
}

if (hasProperty(obj, "a") { // autocompletion is provided
	console.log(obj.a); // `a` is `number | undefined` because it's optional
}

if (hasProperty(obj, "invalid") { // type error here
	console.log(obj.invalid);
}
type ExtractByKeyAndAssertNonUndefined<T, K extends KeysOf<T>> =
	& ExtractByKey<T, K>
	& { [P in K]: Exclude<T[P], undefined> };
export function hasValue<T extends object, K extends KeysOf<T>>(
	obj: T,
	key: K,
): obj is ExtractByKeyAndAssertNonUndefined<T, K> {
	return key in obj && obj[key] !== undefined && obj[key] !== null;
}

if (hasValue(obj, "a") {
	console.log(obj.a); // `a` is `number`
}

Who does this impact? Who is this for?

TypeScript users

@piotrwitek
Copy link
Owner

Hey @raythurnevoid,
Thanks for proposal.

  • hasProperty looks good I will accept PR.
  • hasValue implementation is good, but the name needs refinement as it's not obvious it's reffering to the object property defined value. Please propose some alternatives.
    Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
2 participants