我想知道,是否有可能向使用字符串数组作为键的TypeScript类型添加前缀或后缀。 type First = {
one: string
two: string
}
type Second = keyof First
type Third = {
[S in Second]: any
} 使用这种方法,Third可以接受任何类型的属性one & two。这是惊人的,因为我只需要更改第一个类型,以便让其他类型也更新。 现在我想要第四个类型,它与Third完全相同,但是我想给键添加一个前缀。就像一个美元符号之类的。 期望的结果: type Fourth = {
$
我这样定义一个AbstractModel:
export interface AbstractModel {
[key: string]: any
}
然后我将类型声明为Keys
export type Keys = keyof AbstractModel;
我希望任何具有Keys类型的内容都会被统一地解释为一个字符串,例如:
const test: Keys;
test.toLowercase(); // Error: Property 'toLowerCase' does not exist on type 'string | number'. Pro
我有一个使用keyof特性的简单函数: interface B {
name: string;
age: number;
}
function test(key: keyof B) {}
const c = {
age: 'age'
}
test(c.age); 上面代码的问题是typescript抛出了一个错误,即type string is not assignable to keyof B。 那么,如果keyof特性不能与对象键值一起使用,那么它还有什么意义呢?我不想添加as keyof B。
假设我们有以下枚举 enum PrimayValType {
"string",
"boolean",
"integer",
"float"
} 现在,我想要编写一个函数,该函数输入一个Buffer和一个PrimaryValType类型的参数,并根据PrimaryValType转换缓冲区。如何在Typescript中编写这样的函数? function f(b: Buffer, t: PrimayValType): ??? {
// converts b to a literal based on t
}
是否有方法将字符串映射到TypeScript中匹配的模板文字类型?
下面是一个例子:
type SomeType<T> = {
[P in keyof T as `as${Capitalize<string & P>}`]: number;
};
这应该将x的每个属性都转换为T,并使其成为属性asX。
但是现在我想取一个像foo这样的属性名,并以TypeScript可以检测到的方式将其转换为asFoo。
我希望能够做到这一点:
interface I {
foo: number;
bar: number;
}
const obj: SomeType
我有一个枚举
enum Action {
action1 = 'action1',
action2 = 'action2'
};
其值用作对象中的计算属性名称:
/*
...to be able to use these as values, not just types
*/
const ActionState = {
[Action.action1]: 'actionState1' as const,
[Action.action2]: 'actionState2' as const,
};
我想定义一个类
以下代码会导致错误,因为根据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
我在RN项目中有样式化的组件和typescript Typescript在我的一个文件中抛出了一个奇怪的错误,上面写着Element implicitly has 'any' type because expression of type 'string' can't be used to index 'ColorKeyType' 受影响的代码,错误在return theme.colors[color]部分 const StyledText = styled(Text)<TextStyleProps>`
color: $
假设我有一个字符串枚举:
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
有没有办法用Typescript实现这样的功能呢? class Person {
public name: string;
constructor(data:any) {
this = Object.assign(this, data);
}
}
const p = new Person({name: "Daniel", "age": 30, "gender": "M"});
console.log(p.name) //Daniel
console.log(p.age) //undefined