在TypeScript中,如何设置作为类属性的对象的索引签名?

时间:2017-10-03 23:02:09

标签: typescript

这是一个班级:

export class Survey {
    isCompleted: boolean;
    response: {
        'devices': string[];
        'languages': string[];
        'frameworks': string[];
        'backend': string[];
    };
}

我得到" 元素隐含有一个'任何'键入因为类型' ...'没有索引签名"尝试以下操作时出错:

return Object.keys(user1.response).map(key => {
        return percentageMatch(user1.response[key], user2.response[key]) * categoryScores[key];
    })

user1user2Survey类的实例。

我知道如何使用简单的对象文字设置索引签名但是如何使用response对象的属性来实现它,Survey对象本身是Private Sub CommandButton3_Click() Dim cell As Range, GRN Dim iRow As Long Dim ws As Worksheet Set ws = Worksheets("Sheet1") GRN = Me.textbox_GRN1.Value If WorksheetFunction.CountIf(Sheet1.Range("A:A"), GRN) = 0 Then MsgBox "This is an incorrect GRN" 'Me.textbox_GRN1.Value = "" 'Don't do this! 'It will annoy your users Exit Sub End If Dim rng As Range Set rng = ws.Range("A1").CurrentRegion 'assumes no blank rows/columns in data table Me.textbox_BAY1.Value = Application.VLookup(GRN, rng, 2, False) Me.textbox_ROW1.Value = Application.VLookup(GRN, rng, 3, False) Me.textbox_COLOUM1.Value = Application.VLookup(GRN, rng, 4, False) Me.textbox_PALLET1.Value = Application.VLookup(GRN, rng, 5, False) End Sub 类的属性。

2 个答案:

答案 0 :(得分:6)

这需要向[key: string]: string[]类型添加索引类型response

export class Survey {
    isCompleted: boolean;
    response: {
        [key: string]: string[],
        devices: string[],
        languages: string[],
        frameworks: string[],
        backend: string[],
    };
}

您可以在我创建的TypeScript Playground demo中查看。

您还可以考虑减少重复,并将已知键提取为字符串文字类型:

type ResponseKeys = 'devices' | 'languages' | 'frameworks' | 'backend';

export class Survey {
    isCompleted: boolean;
    response: {
        [key in ResponseKeys]: string[]
    };
}

答案 1 :(得分:1)

索引签名是必需的,因为Object.keys()丢失了类型信息并返回字符串数组。

您可以引入your own function which is similar to Object.keys()但声明为返回实际对象键的数组:

function typedKeys<T>(o: T): (keyof T)[] {
    // type cast should be safe because that's what really Object.keys() does
    return Object.keys(o) as (keyof T)[];
}

然后,如果对象的类型相同,则迭代一个对象的键并访问另一个对象的函数中不会出现错误:

export class Survey {
    isCompleted: boolean;
    response: {
        'devices': string[];
        'languages': string[];
        'frameworks': string[];
        'backend': string[];
    };
}

function f(user1: Survey, user2: Survey) {
    return typedKeys(user1.response).map(key => {
        return user1.response[key] == user2.response[key];
    })
}