Say I have an object of type any
and I want to check if it's an object with the key I am actually expecting. How can I create a function that updates the type of that?
const myObject = transition.options().custom; // custom is type any
if (hasProp('isChanged') && myObject.isChanged) {
// Do something
}
In this case I would like to implement the hasProp
function.
Cause what I do a lot are these three checks and then additinal afterwards. So it would be nice to have a function for it.
if (typeof custom === 'object' && custom != null && 'isChanged' in custom) {
In this case, the function should return the type is an object with the property isChanged
, and isChanged
is unknown.
Thank you.
Say I have an object of type any
and I want to check if it's an object with the key I am actually expecting. How can I create a function that updates the type of that?
const myObject = transition.options().custom; // custom is type any
if (hasProp('isChanged') && myObject.isChanged) {
// Do something
}
In this case I would like to implement the hasProp
function.
Cause what I do a lot are these three checks and then additinal afterwards. So it would be nice to have a function for it.
if (typeof custom === 'object' && custom != null && 'isChanged' in custom) {
In this case, the function should return the type is an object with the property isChanged
, and isChanged
is unknown.
Thank you.
Share Improve this question asked Mar 12 at 10:44 ZachuZachu 474 bronze badges 2 |1 Answer
Reset to default 0You could create a custom type guard that asserts that the first argument is an object with the key as the second argument:
Playground
function hasProp<K extends PropertyKey>(obj: unknown, prop: K): obj is {[k in K]: unknown}{
return typeof obj === 'object' && obj !== null && (prop in obj);
}
if (hasProp(myObject, 'foo') && myObject.foo) {
/*
const myObject: {
foo: unknown;
}
*/
myObject
}
isChanged
prop or do you have different keys? Ie do you need also something likeif (hasProp(obj, "foo") && obj.foo) ...
? – derpirscher Commented Mar 12 at 11:03