我有一个接口,它是作为外部库中其他几个接口的扩展而创建的:
interface LabeledProps extends TextProps, ComponentProps {
id: string;
count: number;
...
}
在代码的另一个地方,我有一个 LabeledProps
类型的对象,我想遍历它的所有属性:
function myFunc(props: LabeledProps):void {
for (let key in props) {
const val = props[key]; // <-- ERROR IS HERE
// do other stuff
}
}
行 const val = props[key]
抛出一个打字稿错误(尽管编译后的代码实际上运行得很好):
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'LabeledProps'.
实现这一目标的正确方法(或方法)是什么?谢谢!
(注意:我知道我可以将 [key: string]: any
添加到接口定义中,这将删除错误消息,但我想要一个实际的修复,而不仅仅是隐藏-错误修复。)
答案 0 :(得分:2)
在这种情况下,您希望成对地迭代对象。有一个有用的实用程序,称为 Object.entries
,可以消除错误。
type LabeledProps = {
name: string,
age: number
}
const obj: LabeledProps = {
name: 'Maks', age: 18
}
for (let [ key, value ] of Object.entries(obj)) {
...
}
答案 1 :(得分:0)
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
vector<int> g[1001];
vector<pair<ll,vector<ll>>> pt;
void dfs(ll st,ll e,ll vis[],vector<ll> rs,ll w){
rs.push_back(st);
if(st == e){
pt.push_back({w*(rs.size()-1),rs});
return;
}
for(auto u : g[st]){
if(vis[u] == 0){
vis[st] = 1;
dfs(u,e,vis,rs,w);
vis[st] = 0;
}
}
}
int main()
{
ll n,m,t,c,u,v;
cin>>n>>m>>t>>c;
while(m--){
cin>>u>>v;
g[u].push_back(v);
g[v].push_back(u);
}
if(n == 1)
cout<<0<<endl;
else if(n == 2)
cout<<t<<endl;
else{
vector<ll> rs;
ll w = c;
ll vis[n+1] = {0};
dfs(1,n,vis,rs,w);
if(pt.size() == 0)
cout<<-1<<endl;
else{
sort(pt.begin(),pt.end());
ll te = 0;
ll nt = 0;
for(int i=1;i<pt[0].second.size();i++){
te += c + (nt-te);
while(nt < te)
nt += t;
}
cout<<te<<endl;
}//else
}
return 0;
}
我同意这里的其他答案和评论。其他人的反应都很好,这只是作为另一种方式提供。