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

typeof - TypeScript Feature: Intersection of Key Names Using keyof Operator - Stack Overflow

programmeradmin9浏览0评论

I am working with the searchParams from url and need to validate params based on an interface I have defined. The searchParams must contains all the keys of the interface otherwise will redirect the user to the home-page.

Now, since TypeScript interfaces don't exist at runtime. They are completely erased during compilation to JavaScript. So it is not possible to use them directly.

So I created an array of strings containing the keys and used it as a validator.

But I don't think this to be a good solution. As it will be hard to maintain in the future if I add new keys in interfaces basically would need to manage the same keys at two places.

Also, Thought of using this directly but the typeScript keyOf operator gives us the union type like "key1" | "key2" | "key3", which checks keys using an OR logic.

Due to this:

  1. We were able to get the Typescript errors while adding new elements in an array of keys.
  2. but there was no error while adding new keys in Interfaces.(because the previous ones already exist in the arrays).

And for a strong check we require the type as "key1" & "key2" & "key3".

I am looking for a solution so that we can couple both the type & this array together, so we don't always have to add a field here in array, when we update the keys in Interface.

发布评论

评论列表(0)

  1. 暂无评论