简体   繁体   English

是否可以通过 Typescript 中的映射类型将文字对象中的值(不是键)作为文字而不是其类型(例如字符串)获取?

[英]Is it possible to get the value (not key) in a literal object as a literal, not its type (such as string) via mapped type in Typescript?

Below, I have a literal object {a:"a"}.下面,我有一个文字对象 {a:"a"}。 I want to extract the value of the object as a literal "a", not its type string, so as to check if some other variables is "a" and not any other string.我想将对象的值提取为文字“a”,而不是它的类型字符串,以便检查其他一些变量是否是“a”而不是任何其他字符串。

However if I use mapped type I only get string, not "a".但是,如果我使用映射类型,我只会得到字符串,而不是“a”。

Is there a way to get the value as a type?有没有办法将值作为类型获取?

const a = {a:"a"}
type trueIfLiteral<T extends string>= string extends T?false:true;

type key = keyof typeof a;
const t1 : trueIfLiteral<key> = true; // key is literal

type val = typeof a[key];
const t2 : trueIfLiteral<val> = false; // val is string

So the question is simply, how can I derive a type:所以问题很简单,我怎样才能派生出一个类型:

type valAsLiteral = "a"

First, to make the object slightly less confusing, let's call it obj with properties key and val :首先,为了使对象稍微不那么令人困惑,让我们将其称为具有属性keyval obj

const obj = { key: "val" };

A problem here is that the object is typed as { key: string } .这里的一个问题是对象的类型为{ key: string } TypeScript has automatically widened the 'val' from 'val' to a string. TypeScript 已自动将'val''val'扩展为字符串。 If you want to prevent that widening, you can declare the object as const :如果你想防止这种扩大,你可以将对象声明as const

const obj = { key: "val" } as const;

This results in your code working, and这会导致您的代码正常工作,并且

type val = typeof obj[key];

produces 'val' (and const t2 : trueIfLiteral<val> = false; // val is string fails, because val is no longer a generic string, but only val )产生'val' (和const t2 : trueIfLiteral<val> = false; // val is string失败,因为val不再是通用字符串,而只是val

To get the value in the emitted JS, not in TS, you can do要在发出的 JS 中获取值,而不是在 TS 中,您可以执行

const val = Object.values(obj)[0];

producing 'val' , typed as 'val' , with no type widening.生成'val' ,类型为'val' ,没有类型扩展。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM