Typescript 如何从嵌套对象获取类型
我想创建一个识别嵌套对象字符串的类型。但是,尝试这样做只会返回一个类型Typescript 如何从嵌套对象获取类型,typescript,Typescript,我想创建一个识别嵌套对象字符串的类型。但是,尝试这样做只会返回一个类型string,而不是特定字符串的数组。正确的方法是什么?请参阅下面的代码。谢谢 interface SampleInterface { allIds: string[]; byId: { [key: string]: string[]; }; } const sampleObject: SampleInterface = { allIds: [ 'foo', 'bar', 'a
string
,而不是特定字符串的数组。正确的方法是什么?请参阅下面的代码。谢谢
interface SampleInterface {
allIds: string[];
byId: {
[key: string]: string[];
};
}
const sampleObject: SampleInterface = {
allIds: [
'foo',
'bar',
'alpha',
'bravo',
'charlie',
],
byId: {
foo: ['hello world'],
bar: ['hello world'],
alpha: ['hello world'],
bravo: ['hello world'],
charlie: ['hello world'],
},
};
type ObjectKeys = keyof typeof sampleObject.byId;
// desired: type ObjectKeys = 'foo' | 'bar' | 'alpha' | 'bravo' | 'charlie';
// actual: type ObjectKeys = string;
const fn = (x: ObjectKeys) => console.log(x);
fn('test'); // no error is returned
sampleObject
属于SampleInterface
类型,因为这是您给它的类型注释。因此,sampleObject.byId
的类型是{[key:string]:string[]}
,这就是您定义接口的方式。因此,sampleObject.byId的类型的keyof是string
简单的解决方案是在没有类型注释的情况下声明sampleObject
,让编译器尽可能具体地推断其类型
这就是说,最好也将SampleInterface
设置为泛型,以便类型检查器强制执行allid
中的字符串与byId
的属性名称相同。如果希望常量的类型使用SampleInterface
,最好的方法是先声明byId
对象,根据该对象的键声明ObjectKeys
类型,然后使用动态创建allid
数组
接口采样接口{
allIds:K[];
byId:记录
}
常量_sampleObjectById={
foo:[“你好,世界”],
酒吧:[“你好,世界”],
阿尔法:[“你好,世界”],
好极了:[“你好,世界”],
查理:[“你好,世界”],
};
//ObjectKeys='foo'|'bar'|'alpha'|'bravo'|'charlie'
类型ObjectKeys=typeof _sampleObjectById的keyof;
常量sampleObject:SampleInterface={
allid:Object.keys(_sampleObjectById)作为ObjectKeys[],
byId:_sampleObjectById
}
//日志['foo','bar','alpha','bravo','charlie']
log(sampleObject.allIds);
sampleObject
属于SampleInterface
类型,因为这是您给它的类型注释。因此,sampleObject.byId
的类型是{[key:string]:string[]}
,这就是您定义接口的方式。因此,sampleObject.byId的类型的keyof是string
简单的解决方案是在没有类型注释的情况下声明sampleObject
,让编译器尽可能具体地推断其类型
这就是说,最好也将SampleInterface
设置为泛型,以便类型检查器强制执行allid
中的字符串与byId
的属性名称相同。如果希望常量的类型使用SampleInterface
,最好的方法是先声明byId
对象,根据该对象的键声明ObjectKeys
类型,然后使用动态创建allid
数组
接口采样接口{
allIds:K[];
byId:记录
}
常量_sampleObjectById={
foo:[“你好,世界”],
酒吧:[“你好,世界”],
阿尔法:[“你好,世界”],
好极了:[“你好,世界”],
查理:[“你好,世界”],
};
//ObjectKeys='foo'|'bar'|'alpha'|'bravo'|'charlie'
类型ObjectKeys=typeof _sampleObjectById的keyof;
常量sampleObject:SampleInterface={
allid:Object.keys(_sampleObjectById)作为ObjectKeys[],
byId:_sampleObjectById
}
//日志['foo','bar','alpha','bravo','charlie']
log(sampleObject.allIds);
因为sampleObject
属于SampleInterface
类型,所以sampleObject.byId
属于{[key:string]:string[]}
类型,因为您就是这样定义接口的。所以keyof
为您提供string
。请尝试删除:SampleInterface
类型批注。因为sampleObject
属于SampleInterface
类型,所以sampleObject.byId
属于{[key:string]:string[]}
类型,因为您就是这样定义接口的。所以keyof
为您提供string
。尝试删除:SampleInterface
类型注释。