gpt4 book ai didi

javascript - typescript 为keyof不工作分配值

转载 作者:行者123 更新时间:2023-12-04 15:36:18 25 4
gpt4 key购买 nike

我有个问题:
- 我没有为变量的值赋值 温度 如下面的代码
请问,如何给变量赋值温度
以下代码:

interface Base {
a: number;
b: number;
c: string;
}

interface Child extends Base {
d: string;
}

const data: Child = {
a: 1,
b: 2,
c: "1",
d: "2"
}

function check<T extends Base>(obj: T, key: string) {
const keys: any[] = Object.keys(obj);
type dataTypes = keyof T;
for (let m in keys) {

// error:
// Type 'string' is not assignable to type 'keyof T'.
// Type 'string' is not assignable to type '"a" | "b" | "c"
const temp: dataTypes = m; //error

}
}

function test(data: Base) {
check(data, "d")
}

最佳答案

Object.keys(obj)返回 string[] , 这就是为什么 m是一个字符串,但 dataTypes"a" | "b" | "c" ( union type ),即更具限制性。所以你不能将字符串赋给 "a" | "b" | "c" 类型的变量.

解决方法很简单:不要使用 Object.keys(obj) :

function check<T extends Base>(obj: T, key: string) {
type dataTypes = keyof T;
for (let m in obj) {
const temp: dataTypes = m;
}
}

关于javascript - typescript 为keyof不工作分配值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59640091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com