相关疑难解决方法(0)

如何从 TypeScript 中的枚举值构建类型?

鉴于以下情况:

enum FooKeys {
  FOO = 'foo',
  BAR = 'bar',
}
Run Code Online (Sandbox Code Playgroud)

我想制作一个这样的界面,但不是手动定义键,而是用枚举的值构建它。

interface Foo {
  foo: string
  bar: string
}
Run Code Online (Sandbox Code Playgroud)

TypeScript 可以实现这样的功能吗?

谢谢!

types typescript typescript-generics

25
推荐指数
4
解决办法
2万
查看次数

你如何在TypeScript中模拟名义输入?

我的项目中有很多函数,它们以数字作为参数; 这个数字是数组索引的一半,另一半时间,它是一个光标位置(数组中两个条目之间的一个点).即使使用命名约定,这也会造成混淆.

我想强制执行以下功能正在采用预期的名义类型.

class Index extends Number {}
class CursorPosition extends Number {}

function getElement(i: Index) {}
function getRange(p1: CursorPosition, p2: CursorPosition) {}

const myIndex: Index = 6;
const myPosition: CursorPosition = 6;

getElement(1); // would like this to fail at compile time
getRange(2, 3); // would like this to fail at compile time
getElement(myPosition); // would like this to fail at compile time
getRange(myIndex, myIndex); // would like this to fail at compile time

getElement(myIndex); // would like this …
Run Code Online (Sandbox Code Playgroud)

casting type-conversion typescript

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