繁体   English   中英

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

[英]TypeScript: How to deal with generic types and the keyof operator

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

传递参数:

  • 记录要更新
  • 财产关键
  • 一个新的数组项

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

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"))

您总是可以通过狡猾(例如,索引访问和假设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都将具有key属性的string[]值,但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]};
}

(注意,由于TypeScript的错误,这仍然很难正确输入)现在该函数只接受key属性为ReadonlyArray<string>类型的东西,并保证key属性出现在返回值中:

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参数推断了一个太宽的类型,强制您在调用站点指定键类型:

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

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

常量声明不能是通用的类型。

所以你的代码会发生变化

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM