在打字稿中获取`keyof`非可选属性名称 [英] get `keyof` non-optional property names in typescript

查看:32
本文介绍了在打字稿中获取`keyof`非可选属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的界面

interface X {
    key: string
    value: number | undefined
    default?: number
}

但我只想要非可选键,也就是.<代码>"键" |"value",或者只是 "key"(两者都适合我)

But I want the non-optional keys only, aka. "key" | "value", or just "key" (both will do fine for me)

type KeyOfX = keyof X 给我 "key" |价值" |默认".

type NonOptionalX = {
    [P in keyof X]-?: X[P]
}

type NonOptionalKeyOfX = keyof NonOptionalX 给出 "key" |价值" |"default" as -? 仅删除可选修饰符并使它们全部为非可选.

type NonOptionalKeyOfX = keyof NonOptionalX gives "key" | "value" | "default" as -? only removes the optional modifier and make all of them non-optional.

ps.我使用打字稿 2.9.

ps. I use Typescript 2.9.

推荐答案

您可以使用 undefined extends k 形式的条件类型运算符?never : knever 替换为 undefined 可以分配给的值的键,然后使用 union T | 的事实.never 只是任何类型的 T :

You can use conditional type operator of the form undefined extends k ? never : k to substitute never for keys of values that undefined could be assigned to, and then use the fact that union T | never is just T for any type:

interface X {
    key: string
    value: number | undefined
    default?: number
}


type NonOptionalKeys<T> = { [k in keyof T]-?: undefined extends T[k] ? never : k }[keyof T];

type Z = NonOptionalKeys<X>; // just 'key'

此评论也可能相关:https://github.com/Microsoft/TypeScript/issues/12215#issuecomment-307871458

这篇关于在打字稿中获取`keyof`非可选属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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