解决打字稿中的类型问题的正确方法是什么

时间:2020-10-19 18:05:37

标签: typescript types typescript-typings

示例:

DispatchQueue.main.async()

但是Typescript编译器说,我不能将“ string”而不是“ TCountryCode”类型传递给该函数。

我的解决方法是:

func testReferences() throws {
    //Define the vars we want to test outside of the auto-release pool statement.
    weak var weakVC: UIViewController
    weak var weakNC: UINavigationController
    autoreleasepool {
        var strongVC: UIViewController? = UIViewController()
        var strongNC: UINavigationController? = UINavigationController(rootViewController: strongVC!)
        weakVC = strongVC
        weakNC = strongNC
        strongVC = nil
        
        XCTAssertNotNil(weakVC)
        XCTAssertNotNil(weakNC)
        
        strongNC = nil
    }
    //Test for nil outside of the autorelasepool statement, 
    //after the auto-release pool is drained.
    XCTAssertNil(weakVC) // fails
    XCTAssertNil(weakNC) // fails
}

或者:

// Types:
type TCountryCode = 'US' | 'RU' | 'KZ' | 'UA'
function doSomethingWithCountryCode(countryCode: TCountryCode): void => { ... }

// Code:
let countyCodes = ['US', 'RU', 'KZ', 'UA']
for (let countryCode of countryCodes) {
    doSomethingWithCountryCode(countryCode)
}

但是它似乎不正确,因为它看起来太糟而且太长了

解决此问题的正确方法是什么?

1 个答案:

答案 0 :(得分:3)

countyCodes定义为const,这样它就不会自动类型扩展:

const countyCodes = ['US', 'RU', 'KZ', 'UA'] as const;

如果需要,还可以使用上面的表达式来定义类型,以减少重复:

type TCountryCode = typeof countyCodes[number];