[英]Typescript ERROR(2322) typescript failed to narrow the type
我試圖添加一個條件運算符來指示 function greet 的返回類型,但收到以下錯誤消息:
輸入“你好? ${T & string}`' 不可分配給類型 'T extends string: string。 細繩[]'? 類型“string”不可分配給類型“T extends string: string”。 細繩[]'。
下面是截圖:
下面是代碼,大家可以復制到Typescript playground進行測試。
// Welcome to the TypeScript Playground, this is a website
// which gives you a chance to write, share and learn TypeScript.
// You could think of it in three ways:
//
// - A location to learn TypeScript where nothing can break
// - A place to experiment with TypeScript syntax, and share the URLs with others
// - A sandbox to experiment with different compiler features of TypeScript
const anExampleVariable = "Hello World"
console.log(anExampleVariable)
// To learn more about the language, click above in "Examples" or "What's New".
// Otherwise, get started by removing these comments and the world is your playground.
function isString(val: any): val is string{
return Object.prototype.toString.call(val) === '[object String]';
}
function greet<T extends string | string[]>(person: T) : T extends string ? string: string[] {
if( isString(person) ){
return `hello! ${person}`;
} else {
return person.map(p=>`hello! ${p}`);
}
}
let greetStr: string = greet('Jhon');
let greetStrAry: string[] = greet(['Jhon', 'Miley']);
console.log(greetStr);
console.log(greetStrAry);
您可以使用function 重載來解決說person
可以是一個string
或string[]
並且返回類型應該相同的困難:
function greet(person: string): string;
function greet(person: string[]): string[];
function greet(person: string | string[]): string | string[] {
if( isString(person) ){
return `hello! ${person}`;
} else {
return person.map(p=>`hello! ${p}`);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.