打字稿抱怨显式类型没有索引签名

时间:2018-12-25 01:41:21

标签: javascript typescript types typescript-typings

Typescript在以下代码上引发错误"Element implicitly has an 'any' type because type 'HumansToDogs' has no index signature."

对我来说,一切似乎都是显而易见的,任何人都可以帮忙吗?

type HumanName = 'Jessie' | 'Mark';
type DogName = 'Spot' | 'Buddy';

type HumansToDogs = {
  [key in HumanName]: DogName;  // Isn't this an index signature?
}

const humansToDogs: HumansToDogs = {
  'Jessie': 'Buddy',
  'Mark': 'Spot',
};

for (const human in humansToDogs) {
  const dog = humansToDogs[human];  // Index signature error here
}

2 个答案:

答案 0 :(得分:2)

for..of将循环变量键入为string。使用noImplicitAny时,无法将索引索引为任意string。最简单的解决方案是使用类型断言:

for (const human  in humansToDogs) {
    const dog = humansToDogs[human as HumanName];  // Index signature error here
}

答案 1 :(得分:0)

您可以明确地让Typescript编译器知道private List<MulticlassClassificationPrediction> Predict<TInputModel>(string modelName, string testDataPath) where TInputModel: class, new() { PredictionEngine<TInputModel, MulticlassClassificationPrediction> predEngine; predEngine = _predEnginePool.GetPredictionEngine(modelName: modelName); IDataView dataView = _mlContext.Data.LoadFromTextFile<TInputModel>( path: testDataPath, hasHeader: true, separatorChar: ',', allowQuoting: true, allowSparse: false); // Use first line of dataset as model input // You can replace this with new test data (hardcoded or from end-user application) var testDataList = _mlContext.Data.CreateEnumerable<TInputModel>(dataView, false).ToList(); List<MulticlassClassificationPrediction> predictionList = new List<MulticlassClassificationPrediction>(); foreach (var testData in testDataList) { MulticlassClassificationPrediction result = predEngine.Predict(testData); predictionList.Add(result); } return predictionList; } 引用了human的键,如下所示:

HumanName

但是更好的方法是定义数据的形状,您可以显式定义一个将索引声明为字符串的新类型:

humansToDogs[human as keyof HumanName]