Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ts - Type 'xxx' is not assignable to type 'never'. #81

Open
NaClYen opened this issue Sep 3, 2021 · 0 comments
Open

ts - Type 'xxx' is not assignable to type 'never'. #81

NaClYen opened this issue Sep 3, 2021 · 0 comments
Assignees

Comments

@NaClYen
Copy link
Owner

NaClYen commented Sep 3, 2021

延伸於 #80 的應用, 加入 assign 的行為就馬上進到另一個無解的死胡同... 😥

先說結論

還是用 any 就好...
沒找到很優雅的解方

code

此情境是外部會給予任何可能的資料物件, 嘗試拿取屬性名稱交集的部分(進一步還需檢驗型別, 但和此議題無關)

const data = { t: 123, g: "rrr" }

function injectData(importedData: any) {
    let k: keyof typeof data;

    for (k in data) {
        if (k in importedData)
            data[k] = importedData[k]
    }
}

errors

Type 'any' is not assignable to type 'never'.

這裡的 never 來自兩個 value 的類型的交集, 也就是 number & string
所以如果使用不同 value 類型的情況, 就放棄型別檢測吧XD

處理

const data = { t: 123, g: "rrr" }

function injectData(importedData: any) {
    let k: keyof typeof data;
    
    for (k in data) {
        if (k in importedData)
            // `(data as any)[k]` 也可過, 但意義不太一樣
            (data[k] as any) = importedData[k];
    }
}
tags: ts typescript
@NaClYen NaClYen self-assigned this Sep 3, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant