interface modal {
name: string;
check: boolean;
}
type Key = "name" | "check";
const obj: modal = fn();
function fn():any {
return {
name: "hello"
}
}
class Modal {
name: string;
check: boolean;
constructor() {
this.name = "";
this.check = false;
Object.keys(obj).forEach((key: string) => {
this[key as keyof modal] = obj[key as keyof modal];
})
}
}
我得到一個錯誤[key as keyof modal]
錯誤訊息:鍵入“字串 | boolean' 不能分配給型別 'never'。型別“字串”不可分配給型別“從不”。

uj5u.com熱心網友回復:
Object.keys總是回來string[],無論如何。當然,Array<keyof typeof obj>在這種情況下預計它會回傳,但事實并非如此。請在 github 上查看此問題串列。
在這種情況下應該做的第一件事是type assertion。
(Object.keys(obj) as Array<keyof typeof obj>)
然而,這還不是結束。這里還是有錯誤:
this[key] = obj[key]; // error
一般來說,TS 不喜歡突變。請參閱我的文章和這個答案。
this[key]和的型別obj[key]是string | boolean。
請看這段代碼:
type Key = "name" | "check";
let _name: Key = 'name'
let _check: Key = 'check'
obj[_name] = obj[_check] // error
上面的代碼幾乎和你的一樣,除了你的變異在迭代器里面而我的不是。迭代索引和型別之間沒有系結key。
參見示例:
(Object.keys(obj) as Array<keyof typeof obj>)
.forEach((key, index) => {
if (index === 0) {
const test = key // keyof modal and not "name"
}
})
這是正確的行為,因為即使 JS 規范也不能保證 firstkey是name. JS 引擎保留按任何順序歸還您密鑰的權利。當然,在 99.99% 的情況下,您會得到預期的訂單,但這并不意味著您有保證。
那么,為什么我們never在錯誤資訊中有呢?TypeScript 使預期鍵(聯合)相交,因為獲得通用型別更安全。交集string & boolean- 給你never,這就是你有這個錯誤資訊的原因。
我相信不使用你能做的最好的事情type assertions就是呼叫reduce:
interface modal {
name: string;
check: boolean;
}
type Key = "name" | "check";
const obj: modal = fn();
function fn(): any {
return {
name: "hello"
}
}
class Modal implements modal {
name: string;
check: boolean;
constructor() {
this.name = "";
this.check = false;
const result = (Object.keys(obj) as Array<keyof typeof obj>)
.reduce((acc, key) => ({
...acc,
[key]: obj[key]
}), this)
Object.assign(this, result)
}
}
Playground
值得使用implements modal或大寫modal的界面。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/414468.html
標籤:
