Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
TypeScript如何创建条件返回类型的函数?_Typescript_Typescript Typings_Typescript Generics_Union Types - Fatal编程技术网

TypeScript如何创建条件返回类型的函数?

TypeScript如何创建条件返回类型的函数?,typescript,typescript-typings,typescript-generics,union-types,Typescript,Typescript Typings,Typescript Generics,Union Types,我想用条件返回类型编写一个函数。如果函数被传递一个'val1'作为参数,它将返回字符串类型,如果'val2'返回数字类型,依此类推 简单例子 游乐场: const存储={ val1:'字符串', val2:1, 瓦尔3:是的 }; INames类型=存储类型的键;//“瓦尔1”|“瓦尔2”|“瓦尔3” const getFromStore=(参数名:INames)=>{ 返回存储区[paramName]; }; const res=getFromStore('val1');//返回类型是stri

我想用条件返回类型编写一个函数。如果函数被传递一个'val1'作为参数,它将返回字符串类型,如果'val2'返回数字类型,依此类推

简单例子

游乐场:

const存储={
val1:'字符串',
val2:1,
瓦尔3:是的
};
INames类型=存储类型的键;//“瓦尔1”|“瓦尔2”|“瓦尔3”
const getFromStore=(参数名:INames)=>{
返回存储区[paramName];
};
const res=getFromStore('val1');//返回类型是string | number | boolean,而不是string
res.split('');//错误
常量存储={
val1:'字符串',
val2:1,
瓦尔3:是的
};
常量getFromStore=(参数名:K)=>{
返回存储区[paramName];
};
const res=getFromStore('val1');
res.split(“”);

拆分函数在字符串上工作,请注意

若要在数字上执行固定功能,请注意

所以,如果您正在以适当的格式转换res和res2,然后应用适当的函数。也许你能得到你期望的结果

我对你的代码做了一些修改。(将res转换为字符串并将res2转换为数字)。请查看您更改的代码和密码

const store = {
    val1: 'string',
    val2: 1,
    val3: true
};

const getFromStore = <K extends keyof typeof store>(paramName: K) => {
    return store[paramName];
};

const res = getFromStore('val1');
res.split('');