最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

typescript - Simplify object type checking via function - Stack Overflow

programmeradmin1浏览0评论

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
  • Is it always a isChanged prop or do you have different keys? Ie do you need also something like if (hasProp(obj, "foo") && obj.foo) ... ? – derpirscher Commented Mar 12 at 11:03
  • key can be different, so the target function I am looking for would be function(thing: any, key: string) {} – Zachu Commented Mar 12 at 13:20
Add a comment  | 

1 Answer 1

Reset to default 0

You 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
}
发布评论

评论列表(0)

  1. 暂无评论