像对象结构一样,数组中键处的Typescript捕获类型

时间:2019-04-07 11:11:10

标签: typescript typescript-typings

让我说一个像这样的结构:

Future _repeatNotification() async {
    var androidPlatformChannelSpecifics = AndroidNotificationDetails(
        'repeating channel id',
        'repeating channel name',
        'repeating description');
    var iOSPlatformChannelSpecifics = IOSNotificationDetails();
    var platformChannelSpecifics = NotificationDetails(
        androidPlatformChannelSpecifics, iOSPlatformChannelSpecifics);
    await flutterLocalNotificationsPlugin.periodicallyShow(0, 'repeating title',
        'repeating body', RepeatInterval.EveryMinute, platformChannelSpecifics);
}

我需要的是与数组相同的结构,但是如何捕获函数中该特定键的类型?

type Dict<T = any> = {[key: string]: T}

type AsObject<T extends Dict> = {
  [K in keyof T]: (x: any) => T[K]
}

1 个答案:

答案 0 :(得分:2)

如果要确保数组项具有typefn的核心组合,则可以使用映射类型为数组项创建所有有效可能性的并集,然后使用定义数组:

type Dict<T = any> = Record<string, T>

type AllPosibilities<T extends Dict> = {
    [K in keyof T]: {
        type: K,
        fn: (x: any) => T[K]
    }
}[keyof T]

type AsArray<T extends Dict> = AllPosibilities<T>[]

let arr : AsArray <{
    "a": string,
    "b": number
}> = [
    { type: "a", fn: (x) => "" }, //ok
    { type: "b", fn: (x) => "" },// err
    { type: "b", fn: (x) => 1 }  //ok
]