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

That's my code, but the return type of colname always Dictory<string> whatever pass any type, how should I correctly use type guard for key-value

1
  • Could you provide the specific values you are passing and where the actual result differs from your expected result? Commented Nov 19, 2018 at 10:09

1 Answer 1

1

The problem is not with the type guard. If you want the function to return a value of the same type you will either need to have multiple overloads, or a type parameter that captures the actual type of the parameter and return the same type parameter:

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; }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.