为什么如果语句更改我的类型定义?

问题描述 投票:0回答:1
signal.write

函数的问题。

这里是我遇到的错误的屏幕截图:

function write(valueOrFn: T | ((value: T) => T)) {
    const newValue: T = typeof valueOrFn === "function" ? valueOrFn(_value) : valueOrFn

    /* This expression is not callable.
       Not all constituents of type '((value: T) => T) | (T & Function)' are callable.
       Type 'T & Function' has no call signatures.ts(2349)
       (parameter) valueOrFn: ((value: T) => T) | (T & Function) */

    if (newValue === _value) return
    _value = newValue

    for (const subscriber of [..._subscribers]) {
        subscriber.notify()
    }
}

在函数的第一行中,

valueOrFn

键入为T | ((value: T) => T)screenshot of the function with the error,但错误消息将其显示为((value: T) => T) | (T & Function)

.
代码没有问题,我不打算在此练习之外使用它,但是此错误表明我错过了一些重要的东西。为什么会发生这种情况,我该如何解决?

there是参考的完整代码:

type Observer = { notify: () => void; link: (unlink: any) => void; }
type Signal = <T>(value:T) => [() => T, (value: T | ((value: T) => T)) => void]

let activeObserver: Observer | null = null

const signal:Signal = <T>(value:T) => {
    let _value: T = value
    const _subscribers: Set<Observer> = new Set()

    function unlink(dep) {
        _subscribers.delete(dep)
    }

    function read() {
        if (activeObserver && !_subscribers.has(activeObserver)) {
            _subscribers.add(activeObserver)
            activeObserver.link(unlink)
        }
        return _value
    }

    function write(valueOrFn: T | ((value: T) => T)) {
        const newValue:T = typeof valueOrFn === "function" ? valueOrFn(_value) : valueOrFn

        if (newValue === _value) return
        _value = newValue

        for (const subscriber of [..._subscribers]) {
            subscriber.notify()
        }
    }

    return [read, write]
}

const effect = (cb: () => void) => {
    let _externalCleanup // defined explicitly by user
    let _unlinkSubscriptions: Set<(Observer) => void> = new Set() // track active signals (to unlink on re-run)

    const effectInstance = { notify: execute, link }

    function link(unlink: (dep:Observer) => void) {
        _unlinkSubscriptions.add(unlink)
    }

    function execute() {
        dispose()
        activeObserver = effectInstance
        _externalCleanup = cb()
        activeObserver = null
    }

    function dispose() {
        if (typeof _externalCleanup === "function") {
            _externalCleanup()
        }
    }

    execute()

    return dispose
}

export { signal, effect }
    
您有

T

在缩小联盟时,您拥有的是ts无法确定它是否可召唤。例如,如果您更改为

any

(转换为非功能类型)。 TS将推断为

any & Function
T extend string
typescript signals
1个回答
0
投票

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.