[英]Typescript function with an argument that gets its keys from another argument
我想創建一個接受兩個 arguments 的 function,第一個是 object,其中包含一個字符串數組,這些字符串是第二個參數的必需字段。 例如
const configOptions = {
config1: {
value: string,
props: ['firstProp', 'secondProp']
}
};
myFunc(configOptions.config1, {
'firstProp': 'first value', // <-- firstProp and secondProp are required because they are defined in config.props
'secondProp': 'second value',
});
我可以通過引用 function 聲明中的特定配置並對配置選項進行 const 斷言來實現這一點
const configOptions = {
config1: {
value: 'a string value',
props: ['firstProp', 'secondProp']
}
} as const;
function myFunc<T extends typeof configOptions.config1>(
option: T,
params: { [key in typeof option.props[number]]: string }
) {}
myFunc(configOptions.config1, {
firstProp: 'first value',
secondProp: 'second value',
});
但我想更通用地實現這一點,所以我可以調用相同的 function 並使用許多配置之一。 這可能嗎?
這是一個stackblitz https://stackblitz.com/edit/typescript-ydyt4v
使用帶有約束的泛型將允許推斷config
的類型。 然后可以使用此推斷的泛型來定義第二個參數的類型。
const configOptions = {
config1: {
value: 'string',
props: ['firstProp', 'secondProp']
},
config2: {
value: 'string',
props: ['one', 'two']
}
} as const;
// Define the base shape (most general shape) of the config.
// I used the const assertion (`as const`) above so defining the props as
// readonly made this work nicely but that could be changed.
interface BaseConfig {
value: string;
props: readonly string[]
}
const myFunc = <
// Define a generic `Config` that adheres (extends) the base shape (BaseConfig).
// It represents the first argument and is inferred from the passed `config`.
Config extends BaseConfig
>(
config: Config,
// Define the input values type based on the passed `Config`.
// Specifically, we want the values of the props key.
// And those keys are for a record, with a string value.
values: Record<Config["props"][number], string>
) => {
// TODO: implement as needed.
return null;
}
// Okay.
myFunc(configOptions.config1, {
'firstProp': 'first value',
'secondProp': 'second value',
});
// Property 'secondProp' is missing in type.
myFunc(configOptions.config1, {
'firstProp': 'first value',
});
// Okay.
myFunc(configOptions.config2, {
'one': '1',
'two': '2'
});
// Property 'one' is missing in type.
myFunc(configOptions.config2, {
'two': '2'
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.