根据Typescript中的字符串推断类型

时间:2020-04-27 09:24:10

标签: typescript

考虑以下代码,

func routeToAddParticipants(existingParticipants: [String], selectedContacts: @escaping ([ContactViewModel]) -> Void) {
    var viewController: UIViewController?

    viewController = self.submodules.addParticipantModule(existingParticipants, false, nil){ [weak self] selectedParticipants in
        self?.viewController.navigationController?.popViewController(animated: true)
        viewController = nil
        guard selectedParticipants?.count ?? 0 > 0 else {
            return
        }
        selectedContacts(selectedParticipants!)
    }
    if let addParticipantViewController = viewController {
        self.viewController.navigationController?.pushViewController(addParticipantViewController, animated: true)
    }
}
navigationItem.searchController = searchController // added searchcontroller in current.

将鼠标悬停在function returnValue(key: string) { return { [key]: key } } const test = returnValue('try') 上时,工具提示如下:

enter image description here

我们可以根据传入的字符串来推断test部分吗?像这样:

enter image description here(这是模拟类型,并不意味着我已解决它...)

1 个答案:

答案 0 :(得分:0)

不确定我是否正确理解了您的问题,因为我不清楚<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>应该具有哪个

在我看来,不进行强制转换是没有办法的,但是使用key可以使用泛型,扩展字符串(同时仍然保持完全动态的键入)来实现:

as