相关疑难解决方法(0)

为什么Object.keys不返回TypeScript中的keyof类型?

标题说明了一切-为什么Object.keys(x)在TypeScript 中不返回类型Array<keyof typeof x>?就是这样Object.keys做的,因此对于TypeScript定义文件作者来说,似乎很明显的疏忽是不将返回类型简单地设为keyof T

我应该在他们的GitHub存储库上记录错误,还是继续发送PR为其进行修复?

typescript

32
推荐指数
3
解决办法
2410
查看次数

如何在 Typescript 中获取输入的 Object.entries() 和 Object.fromEntries?

当我在打字稿中使用Object.fromEntries(entries)orObject.entires(obj)来表示类型/常量entries数组或objt对象时,我会丢失类型any或广泛类型。

在某些情况下,我可以手动分配通用类型(例如Record<string, number>),但是设置每对/键的类型很繁琐。

这是我想要的一个例子。

类型化 Object.fromEntries(entries)

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)

类型化 Object.entries(obj)

const myOldObject = {
    x: 6,
    y: "apple",
    z: true
};

// The type of …
Run Code Online (Sandbox Code Playgroud)

arrays object typescript

16
推荐指数
2
解决办法
1万
查看次数

打字稿类型字符串不可分配给类型 keyof

我有以下代码:

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)因为我会失去类型保护。

typescript

6
推荐指数
2
解决办法
8145
查看次数

如何编写 PickByValue 类型?

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)

typescript

5
推荐指数
1
解决办法
490
查看次数

TypeScript:将对象条目映射到类型

作为打字稿新手用户,我什至在提出问题时都遇到困难,所以请耐心等待。

我试图创建一个 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)

generics type-inference typescript typescript-generics

5
推荐指数
1
解决办法
3816
查看次数