TypeScript:如何处理泛型类型和keyof运算符

时间:2017-07-22 19:47:17

标签: typescript generics generic-programming keyof

我尝试编写一个泛型函数,汇总数据库更新的更新数据。

传递参数:

  • 要更新的记录
  • 属性键
  • 新的数组项

即使我使用keyof R限制密钥的类型,我也无法将具有该密钥的新对象分配给Partial<R>常量。我收到错误Type '{ [x: string]: any[]; }' is not assignable to type 'Partial<R>'. 如何使以下代码生效?如果我用非泛型类型替换泛型类型R,它可以工作。但这不是我需要的。

Snippet on TypeScript Playground

interface BaseRecord {
    readonly a: ReadonlyArray<string>
}

function getUpdateData<R extends BaseRecord>(record: R, key: keyof R, newItem: string) {
    const updateData: Partial<R> = { [key]: [...record[key], newItem] }
    return updateData
}

interface DerivedRecord extends BaseRecord {
    readonly b: ReadonlyArray<string>
    readonly c: ReadonlyArray<string>
}
const record: DerivedRecord = { a: [], b: [], c: ["first item in c"] }
console.log(getUpdateData<DerivedRecord>(record, "c", "second item in c"))

2 个答案:

答案 0 :(得分:9)

你总是可以通过狡猾(例如,索引访问和编译器,假设R[key]是读写的)来弯曲类型系统。

function getUpdateData<R extends BaseRecord>(record: R, key: keyof R, newItem: string) {
    var updateData: Partial<R> = {};
    updateData[key] = [...record[key], newItem]; 
    return updateData
}

或暴力(通过any类型):

function getUpdateData<R extends BaseRecord>(record: R, key: keyof R, newItem: string) {
    const updateData: Partial<R> = <any> { [key]: [...record[key], newItem] }
    return updateData
}

以上回答了你的问题,但要小心:这个功能并不安全。它假定传入的任何record将具有string[]属性的key值,但类型R可能不会。例如:

interface EvilRecord extends BaseRecord {
    e: number;
}
var evil: EvilRecord = { a: ['hey', 'you'], e: 42 };
getUpdateData(evil, 'e', 'kaboom');  // compiles okay but runtime error 

此外,返回值类型Partial<R>有点过宽:您知道它将具有key键,但您需要检查它是否为var updatedData = getUpdateData<DerivedRecord>(record, "c", "first item in c") // Partial<DerivedRecord> updatedData.c[0] // warning, object is possibly undefined 打字系统要快乐:

getUpdateData()

我建议像这样输入type KeyedRecord<K extends string> = { readonly [P in K]: ReadonlyArray<string> }; function getUpdateData<K extends string, R extends KeyedRecord<K>=KeyedRecord<K>>(record: R, key: K, newItem: string) { return <KeyedRecord<K>> <any> {[key as string]: [...record[key], newItem]}; }

key

(请注意,由于a bug in TypeScript,这仍然很难正确输入)现在该函数只接受ReadonlyArray<string>属性类型为key的内容,并保证{{} 1}}属性出现在返回值中:

var evil: EvilRecord = { a: ['hey', 'you'], e: 42 };
getUpdateData(evil, 'e', 'kaboom'); // error, number is not a string array

var updatedData = getUpdateData(record, "c", "first item in c") // KeyedRecord<"c">
updatedData.c[0] // no error

希望有所帮助。

技术更新

我将上面建议的getUpdateData()声明更改为有两个通用参数,因为出于某种原因,TypeScript在推断key参数的过宽类型之前,强制您指定密钥类型at呼叫站点:

declare function oldGetUpdateData<K extends string>(record: KeyedRecord<K>, key: K, newItem: string): KeyedRecord<K>;
oldGetUpdateData(record, "c", "first item in c"); // K inferred as 'a'|'b'|'c', despite the value of 'c'
oldGetUpdateData<'c'>(record, "c", "first item in c"); // okay now 

通过添加第二个泛型,我显然在正确推断密钥类型后延迟了TypeScript对记录类型的推断:

getUpdateData(record, "c", "hello"); // K inferred as 'c' now

随意忽略这一点,但这就是用启发式推理制作香肠的方式。

答案 1 :(得分:0)

常量声明不能是通用的。

所以你的代码更改将是

function getUpdateData<R extends BaseRecord>(record: R, key: keyof R, newItem: string) {
    const updateData:Partial<DerivedRecord> = {
        [key]: [...record[key], newItem]
    };

function getUpdateData<R extends BaseRecord>(record: R, key: keyof R, newItem: string) {
    const updateData = {
        [key]: [...record[key], newItem]
    };

function getUpdateData<R extends BaseRecord>(record: R, key: keyof R, newItem: string) {
   type PartRecord = Partial<DerivedRecord>;
   const updateData: PartRecord = {
    [key]: [...record[key], newItem]
};

return updateData;
}