所以我想找到一种方法来拥有嵌套对象的所有键。
我有一个在参数中采用类型的泛型类型。我的目标是获取给定类型的所有键。
在这种情况下,以下代码运行良好。但是当我开始使用嵌套对象时,情况就不同了。
type SimpleObjectType = {
a: string;
b: string;
};
// works well for a simple object
type MyGenericType<T extends object> = {
keys: Array<keyof T>;
};
const test: MyGenericType<SimpleObjectType> = {
keys: ['a'];
}
Run Code Online (Sandbox Code Playgroud)
这是我想要实现的目标,但它不起作用。
type NestedObjectType = {
a: string;
b: string;
nest: {
c: string;
};
otherNest: {
c: string;
};
};
type MyGenericType<T extends object> = {
keys: Array<keyof T>;
};
// won't works => Type 'string' is not assignable to type 'a' | …Run Code Online (Sandbox Code Playgroud) 我有数据类型的下一个数据
type Data = {
Id: string,
LogicalName: string,
VATRegistered: {
Label: string | null,
Value: number | null,
}
}
const data: Data = {
Id: 'qK1jd828Qkdlqlsz8123assaa',
LogicalName: 'locale',
VATRegistered: {
Label: 'AT401',
Value: 1000001
}
}
Run Code Online (Sandbox Code Playgroud)
我必须将其转换为下一个:
const transformedData = {
Id: 'qK1jd828Qkdlqlsz8123assaa',
LogicalName: 'locale',
VATRegisteredLabel: 'AT401',
VATRegisteredValue: 1000001
}
Run Code Online (Sandbox Code Playgroud)
我编写了一个函数,它必须转换我的对象并以下一个类型返回它
type TransformedData {
Id: string,
LogicalName: string,
VATRegisteredLabel: string | null,
VATRegisteredValue: number | null
}
Run Code Online (Sandbox Code Playgroud)
我的功能:
const _isNull = (value: any) => {
let res = …Run Code Online (Sandbox Code Playgroud) 我想扁平化对象并将返回值转换为类型。
例如:
const myObject = {
names: {
title: 'red',
subtitle: 'green'
},
}
const returned = [...Object.values(flatten(myObject))] as const
// returns ['red', 'green']
type Type = typeof returned[number]
Run Code Online (Sandbox Code Playgroud)
现在返回的变量是 ['red', 'green']
类型应为“红色|” 'green',但现在是一个字符串数组,因为返回的 typeof 是 string[]。我想使用这种类型为我的组件输入 prop:
<Component name="red" /> //is correct, but
<Component name=`something different than "red" or "green"` /> //is incorrect.
Run Code Online (Sandbox Code Playgroud)
压平函数:
type FlattenedObject = { [x: string]: string }
export const flattenDaisyChain = (obj: any): FlattenedObject => {
const result: FlattenedObject = {}
const transform = …Run Code Online (Sandbox Code Playgroud)