type Dircory<T> {
[key:string]: T
}
function colname(columns:Array<string> | string| Dictory<string>, name){
if(Array.isArray(columns){
return columns.map(column=>table_name + "." + columns);
}else if(typeof columns == "string"){
return table_name + "." + columns;
}else if(typeof columns == "object"){
return columns as Dictory<string>
}
}
那是我的代码,但是colname
的返回类型总是Dictory<string>
,无论传递任何类型,我该如何正确地使用键值保护类型
答案 0 :(得分:1)
问题不在于类型防护。如果要让函数返回相同类型的值,则可能需要多次重载,或者需要一个类型参数来捕获参数的实际类型并返回相同类型的参数:
type Dircory<T> = {
[key: string]: T
}
let table_name;
function colname<T extends Array<string> | string | Dircory<string>>(columns: T, name: string) :T
function colname(columns: Array<string> | string | Dircory<string>, name) {
if (Array.isArray(columns)) {
return columns.map(column => table_name + "." + columns);
} else if (typeof columns == "string") {
return table_name + "." + columns;
} else if (typeof columns == "object") {
return columns as Dircory<string>
}
}
let a = colname("A", ""); // string, actually the string literal type "A", but will work with strnig vars too
let arr = colname(["A"], ""); // string[]
let d = colname({a: "A"}, ""); // { a: string; }