2015-10-20 181 views
0

我是新来的TypeScript。获取对象属性

如何解决这个问题:

layout[self._swapEntries ? '_rows' : 'rows'].slice(0, layout.numRowsToDraw); 

错误:

error TS7017: Index signature of object type implicitly has an 'any' type. 

另一个问题:

let entries = rows.selectAll("g." + Legend.LEGEND_ENTRY_CLASS).data((d) => d); 

错误2:

error TS2345: Argument of type '(d: {}) => {}' is not assignable to parameter of type '(datum: {}, index: number, outerIndex: number) => {}[]'. 
Type '{}' is not assignable to type '{}[]'. 
Property 'length' is missing in type '{}'. 

回答

1

你可以做两件事情之一:

interface ILayout { 
    [index: string]: string[] | number, // And any other types which your object returns 
    numRowsToDraw: number 
} 

var layout = { 
    numRowsToDraw: 10 
}; 

然后你的访问属性显式强制转换为数组:

  1. 与接口的layout对象实现一个强类型定义:

    (<string[]>layout[self._swapEntries ? '_rows' : 'rows']).slice(0, layout.numRowsToDraw); 
    
    1. 使用--suppressImplicitAnyIndexErrors标志,告诉你希望被允许使用在编译时不知道一个类型的访问对象键编译
+0

你知道这里有什么问题: 错误TS2345:类型的参数“( d:{})=> {}'不能分配给类型为'(datum:{},index:number,outerIndex:number)=> {} []'的参数。 类型“{}”不可分配为键入“{} []”。 类型“{}”中缺少属性“长度”。 – puppeteer701