在 TypeScript 中将单个属性设为可选 [英] Make a single property optional in TypeScript

查看:99
本文介绍了在 TypeScript 中将单个属性设为可选的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 TypeScript 中,2.2...

In TypeScript, 2.2...

假设我有一个 Person 类型:

Let's say I have a Person type:

interface Person {
  name: string;
  hometown: string;
  nickname: string;
}

我想创建一个返回一个人的函数,但不需要昵称:

And I'd like to create a function that returns a Person, but doesn't require a nickname:

function makePerson(input: ???): Person {
  return {...input, nickname: input.nickname || input.name};
}

input 的类型应该是什么?我正在寻找一种动态方式来指定与 Person 相同的类型,除了 nickname 是可选的 (nickname?: string | undefined).到目前为止,我想出的最接近的事情是:

What should be the type of input? I'm looking for a dynamic way to specify a type that is identical to Person except that nickname is optional (nickname?: string | undefined). The closest thing I've figured out so far is this:

type MakePersonInput = Partial<Person> & {
  name: string;
  hometown: string;
}

但这并不是我想要的,因为我必须指定所有必需的类型,而不是可选的类型.

but that's not quite what I'm looking for, since I have to specify all the types that are required instead of the ones that are optional.

推荐答案

你也可以这样做,只对部分键进行部分操作.

You can also do something like this, partial only some of the keys.

type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>
type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>

interface Person {
  name: string;
  hometown: string;
  nickname: string;
}

type MakePersonInput = PartialBy<Person, 'nickname'>

这篇关于在 TypeScript 中将单个属性设为可选的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆