在TypeScript中,类型声明可以允许动态对象属性?
class Animal {
name: string;
[everything else]: any;
}
let animal = <Animal>{ name: "Kitty", type: "cat" };
animal.name; // Would be treated as string
animal.type; // Would allow compilation and be treated as any
我希望动态地允许这些额外的属性,而不必将它们添加到
我正在尝试使用Enum值作为对象的键,希望它在得到值时保留类型,但我得到的是Element implicitly has an 'any' type because expression of type 'string' can't be used to index type。
export enum TaskType {
Classification = 'classification',
Extraction = 'extraction'
}
const comparisons: { [name in Task
问题是,我希望使用枚举作为字典的键,但我希望使用循环动态生成条目。但是我不喜欢使用?操作符,因为我知道我会填充所有的键,并且我不想强制对每个调用进行!计算。
enum Students {
A,
B,
C,
// many many students
}
// class Info(); // some properties like grades and teacher
const studentInfo: { [key in Students]: Info }; // won't work const must be initialized
const studen
我有一个枚举,我想像解析对象一样解析它。我真的很喜欢Swift编程语言,你只需要使用.rawValue来获取枚举成员(i.e. HelloWorld.one.rawValue = "this is one")的字符串值,但是我还不能理解如何在Typescript中做到这一点。 enum HelloWorld {
one = "this is one",
two = "two",
three = "the third"
}
const getStringFromEnum = (num: HelloWor
我有一个函数,它接受一个参数,该参数的类型在typescript中有几个不同的枚举。我想检查参数是哪种枚举类型。有没有可能检查一下?下面是一个示例代码:
enum X {
ONE,
TWO
}
enum Y {
THREE,
FOUR
}
function check(arg1: X | Y) {
if (arg1 is X) {
// do something with X
}
if (arg1 is Y) {
// do something with Y
}
}
在尝试对数值枚举进行比较时,我注意到一个错误,其中枚举值被转换为字符串类型。这是一种预期的行为吗?
enum Test {
a = 0,
b = 1
}
console.log(Test.a === Test[0]);
// ^ This condition will always return 'false' since the types 'Test' and 'string' have no overlap.(2367)
TypeScript版本:v4.6.4
以下代码会导致错误,因为根据TypeScript,类型Pick<Test<T>, Exclude<keyof T, "someKey">>不能赋值给T。当我推断这种类型时,它应该被赋值给T,有没有办法让TypeScript同意我的观点?或者这只是突破了TypeScript中泛型类型的界限,因为不是动态类型的变体可以正确编译。 type Test<T = {}> = T & {
someKey: string
};
function extract<T>(props: Test<T>): T
假设我有一个字符串枚举:
enum Color {
None = "Q",
Red = "R",
Green = "G",
Blue = "B",
}
现在,在TypeScript,中,我无法编写Color["Q"]来获得潜在的Color返回。我尝试声明自己的助手函数:
type StringEnum = {[key: string]: string};
function lookup<E extends StringEnum>(stringEnum: E, s: str