data我要在 Typescript 中鍵入的物件內部有一個屬性。它如下所示:
type MyThing = {
data: {
options: {
myKey: string,
myValue: string
}[],
key: 'myKey',
value: 'myValue'
}
}
我希望能夠使用泛型實體化這種結構的型別,但不能完全圍繞我應該做什么。以下是要求:
key并且value是必須提供的基本“密鑰”,但可能還有其他:description例如options應該始終是一個物件陣列,其中僅包含 、 和 的值key,value并且可能description在下面定義
我從字面上輸入這個沒有問題(就像上面的例子一樣)。但是,如果我想提供自定義鍵和值(分別為“myKey”和“myValue”),或者如果我想指定其他選項,例如鍵和值之外的描述,我不知道該怎么做。
所需的解決方案是讓我做這樣的事情:
type MyThing = {
data: DataComposer<['key', 'value']>
// data: DataComposer<['key', 'value', 'description', ...]>
}
uj5u.com熱心網友回復:
我想你想要這樣的型別:
type DataComposer<
K extends string,
V extends string,
OtherKeys extends Record<string, string> = Record<never, string>
> = {
data: {
options: { [optionKey in K | V | OtherKeys[keyof OtherKeys]]: string}[],
key: K,
value: V,
} & { [OtherKey in keyof OtherKeys]: OtherKeys[OtherKey] }
}
這K是 和 的key字串V文字value。然后它接受用于映射其他自定義屬性的第三個引數。
你像這樣使用它:
type MyThing = DataComposer<'myKey', 'myValue'>
/*
type MyThing = {
data: {
options: {
myKey: string;
myValue: string;
}[];
key: "myKey";
value: "myValue";
};
}
*/
type MyThingWithOther = DataComposer<'myKey', 'myValue', { foo: 'myFoo' }>
/*
type MyThingWithOther = {
data: {
options: {
myKey: string;
myValue: string;
myFoo: string;
}[];
key: "myKey";
value: "myValue";
foo: 'myFoo';
};
}
*/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/464715.html
標籤:打字稿
上一篇:如何在打字稿中反轉文本?
