标题说明了一切-为什么Object.keys(x)
在TypeScript 中不返回类型Array<keyof typeof x>
?就是这样Object.keys
做的,因此对于TypeScript定义文件作者来说,似乎很明显的疏忽是不将返回类型简单地设为keyof T
。
我应该在他们的GitHub存储库上记录错误,还是继续发送PR为其进行修复?
当我在打字稿中使用Object.fromEntries(entries)
orObject.entires(obj)
来表示类型/常量entries
数组或objt
对象时,我会丢失类型any
或广泛类型。
在某些情况下,我可以手动分配通用类型(例如Record<string, number>
),但是设置每对/键的类型很繁琐。
这是我想要的一个例子。
const myArrayOfPairs = [["a", 5], ["b", "hello"], ["c", false]] as const;
// The type of the following is "any"
const myTypelessObject = Object.fromEntries(myArrayOfPairs);
// I want the type of this one to be: { a: 5; b: "hello"; c: false; }
const myTypedObject = createTypedObjectFromEntries(myArrayOfPairs);
Run Code Online (Sandbox Code Playgroud)
const myOldObject = {
x: 6,
y: "apple",
z: true
};
// The type of …
Run Code Online (Sandbox Code Playgroud) 我有以下代码:
const KeyboardEventKeys = {
Escape: 'Escape',
Enter: 'Enter',
Tab: 'Tab'
};
type KeyboardEventKeys = keyof (typeof KeyboardEventKeys);
function doSomething(key: KeyboardEventKeys) {}
Run Code Online (Sandbox Code Playgroud)
当我将对象属性之一的值传递给函数时,它会对我大喊大叫:
doSomething(KeyboardEventKeys.Enter);
Run Code Online (Sandbox Code Playgroud)
一种解决方案是 cast as KeyboardEventKeys
,但这是一个多余的解决方案。没有它我怎么办?
我也不想添加,doSomething(key: KeyboardEventKeys | string)
因为我会失去类型保护。
该Pick
类型包含在 TypeScript 中。它的实现如下:
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
Run Code Online (Sandbox Code Playgroud)
你将如何编写一个PickByValue
类型,以便以下工作:
type Test = {
includeMe: 'a' as 'a',
andMe: 'a' as 'a',
butNotMe: 'b' as 'b',
orMe: 'b' as 'b'
};
type IncludedKeys = keyof PickByValue<Test, 'a'>;
// IncludedKeys = 'includeMe' | 'andMe'
Run Code Online (Sandbox Code Playgroud) 作为打字稿新手用户,我什至在提出问题时都遇到困难,所以请耐心等待。
我试图创建一个 key => [string + valueObject 接口] 字符串和 valueObjects (作为类型)的映射,然后有一个函数,它根据传递的键强制执行 valueObject 接口。
我觉得最好用一个例子来解释:
// This is an pseudo example stub, not actually working
type ReplaceableWith<T> = string;
// ^ the type I'd like to enforce as the argument
const templates = {
// templateId // template // define somehow the interface required for this template
'animal.sound': 'A {animal} goes {sound}' as ReplaceableWith<{ animal: string; sound: string}>
};
function renderTemplate(
templateId , // must be a key of templates
params …
Run Code Online (Sandbox Code Playgroud)