Deep Object Change Handlers in Typescript

栏目: IT技术 · 发布时间: 3年前

内容简介:Typescript’s ability to deeply-type objects is incredibly handy: it gives you confidence that you’re accessing the right keys on an object and that you’re using those keys as the right types. However, this typing doesn’t come for free: it can add complexit

Deep Object Change Handlers in Typescript

Typescript’s ability to deeply-type objects is incredibly handy: it gives you confidence that you’re accessing the right keys on an object and that you’re using those keys as the right types. However, this typing doesn’t come for free: it can add complexity to things like change handlers. In this post, we’ll write a deep object change handler that both allows us to specify deep object types and satisfies the Typescript compiler.

A Sample Deep Object Type

Let’s use the following Settings type as an example. It contains some visual settings about our app and some information about our user.

type Settings = {
  display: {
    mode: 'light' | 'dark';
  };
  user: {
    name: string;
    age: number;
    admin: boolean;
  };
};

We can then create a sample object that satisfies this type. Let’s use the following example.

const settings: Settings = {
  display: {
    mode: 'dark',
  },
  user: {
    name: 'Betty',
    age: 27,
    admin: false,
  },
};

Writing a Change Handler

So what if we want a change handler that will change any property two levels deep in this object? The secret lies in the use of Generics. We can specify that our key is of type K , where K extends keyof Settings . Likewise, we can specify that our subkey is of type S , where S extends keyof Settings[K] .

Putting this all together, we get the following change handler!

const updateSettings = <K extends keyof Settings, S extends keyof Settings[K]>(
  key: K,
  subkey: S,
  value: Settings[K][S]
): Settings => {
  const newSettings = {
    ...settings,
    [key]: {
      ...settings[key],
      [subkey]: value,
    },
  };

  return newSettings;
};

And there we have it: a framework by which we can update deep types and keep our Typescript compiler happy!


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

C语言的科学和艺术

C语言的科学和艺术

罗伯茨 / 翁惠玉 / 机械工业出版社 / 2005-3 / 55.00元

《C语言的科学和艺术》是计算机科学的经典教材,介绍了计算机科学的基础知识和程序设计的专门知识。《C语言的科学和艺术》以介绍ANSI C为主线,不仅涵盖C语言的基本知识,而且介绍了软件工程技术以及如何应用良好的程序设计风格进行开发等内容。《C语言的科学和艺术》采用了库函数的方法,强调抽象的原则,详细阐述了库和模块化开发。此外,《C语言的科学和艺术》还利用大量实例讲述解决问题的全过程,对开发过程中常见......一起来看看 《C语言的科学和艺术》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具